[loggers]
keys=root,sampleLogger
[handlers]
keys=consoleHandler,fileHandler
[formatters]
keys=sampleFormatter,complexFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_sampleLogger]
level=DEBUG
handlers=consoleHandler,fileHandler
qualname=sampleLogger
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=sampleFormatter
args=(sys.stdout,)
[handler_fileHandler]
class=logging.handlers.RotatingFileHandler
level=DEBUG
formatter=complexFormatter
args=('logs/logfile.txt','a',1048576, 20, 'utf-8')
[formatter_sampleFormatter]
format=%(asctime)s [%(levelname)s] [%(filename)s %(funcName)s line:%(lineno)d] %(message)s
[formatter_complexFormatter]
format=%(asctime)s [%(levelname)s] [%(filename)s %(funcName)s line:%(lineno)d] [%(process)d-%(thread)d] %(message)s
上述配置实现了两种日志输出方式,一种是控制台输出(info及以上级别),另一种是文件输出(debug及以上级别),文件输出的路径可自行替换,其中args=('logs/logfile.txt','a',1048576, 20, 'utf-8')
的含义是:日志文件保存路径,写入方式为’a’(追加),文件大小最大为1M,最多可滚动生成20个日志文件,编码是utf-8。
import logging.config
def my_logger():
"""
自定义的日志模块
:return: Logger对象
"""
logging.config.fileConfig(fname='conf/log_config.ini', disable_existing_loggers=False)
logger_obj = logging.getLogger("sampleLogger")
return logger_obj
上述的fname是日志配置文件的路径
if __name__ == "__main__":
logger = my_logger()
logger.exception('error message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')