Python Logger使用

1. 單文件的logging配置python

import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='znifeng.log',
filemode='w')

 

2. 項目的logger配置(一個logger配置多個handler以實現輸出不一樣級別的日誌到不一樣文件)python2.7

#!/usr/bin/python
# -*- coding: utf-8 -*
__author__ = 'zni.feng'
import os
# mac 上logging的源碼路徑 /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging
import logging
import logging.handlers

class Logger:
    def __init__(self, name="root"):
        self._logger = logging.getLogger(name)
        #def __init__(self, fmt=None, datefmt=None)
        formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] - %(filename)s(line:%(lineno)d) - %(message)s', '%Y-%m-%d %H:%M:%S')

        #class logging.handlers.TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
        handler_info = logging.handlers.TimedRotatingFileHandler('logs/info.log', when='D', interval=1)
        handler_warn = logging.handlers.TimedRotatingFileHandler('logs/warn.log', when='D', interval=1)

        handler_info.setFormatter(formatter)
        handler_warn.setFormatter(formatter)

        #當handler的log level高於logger自己的log level時,此設置纔會生效
        handler_info.setLevel(logging.INFO)
        handler_warn.setLevel(logging.WARN)

        self._logger.addHandler(handler_info)
        self._logger.addHandler(handler_warn)

        #默認狀況下,logger自己的log level是warn,爲了讓info handler的level等級生效,因此調低logger自己的level
        self._logger.setLevel(logging.INFO)
        
    def getLogger(self):
        return self._logger
相關文章
相關標籤/搜索