logging模块

2016-06-20  本文已影响0人  一斤杨梅三两小虫

logging模块主要有以下几个对象

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)  //默认是ERROR级别,所以INFO和DEBUG是打不出来的
fh = logging.FileHandler('/tmp/test.log')
ch = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

目前用不到,暂时忽略

几个对象之间的关系

fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)

总结

定义formatter——决定输出格式
定义handler——决定输出位置
定义logger——最终程序调用的日志接口

将formatter绑定到handler上;再将handler绑定至logger上
这样就可以使用logger对象进行输出日志了。如:logger.info('test')

可以直接使用以下的配置文件

[loggers]
keys = root
  
[handlers]
keys = console, info, error

[formatters]
keys = baseFormatter

[logger_root]
level = NOTSET
handlers = console, info, error
propagate = 0

[handler_console]
level = NOTSET
class = StreamHandler
formatter = baseFormatter
args = (sys.stdout,)

[handler_info]
level = INFO
class = handlers.TimedRotatingFileHandler
formatter = baseFormatter
args = ('./log/info.log', 'midnight', 1)

[handler_error]
level = ERROR
class = handlers.TimedRotatingFileHandler
formatter = baseFormatter
args = ('./log/error.log', 'midnight', 1)

[formatter_baseFormatter]
format = %(asctime)s %(levelname)s %(message)s

使用方法如下

import logging
import logging.config

logging.config.fileConfig('/Users/sgrchan/Downloads/logging.ini')
logger = logging.getLogger()

logger.info('test')
上一篇下一篇

猜你喜欢

热点阅读