loyalxuan 发表于 2017-4-26 10:11:40

使用Python的logging.config

使用Python的logging.config

Python的logging模块接口仿log4j,概念上一致,使用上相当方便。
利用logging.config.fileConfig(),可以将日志的配置用文件来描述,简化了日志的初始化。

例程:
#test.py
importlogging
importlogging.config

logging.config.fileConfig("logging.conf")

#createlogger
logger=logging.getLogger("example")

#"application"code
logger.debug("debugmessage")
logger.info("infomessage")
logger.warn("warnmessage")
logger.error("errormessage")
logger.critical("criticalmessage")

logHello=logging.getLogger("hello")
logHello.info("Helloworld!")



配置文件示例如下:
#logging.conf

[loggers]
keys=root,example

[handlers]
keys=consoleHandler,rotateFileHandler

[formatters]
keys=simpleFormatter

[formatter_simpleFormatter]
format=[%(asctime)s](%(levelname)s)%(name)s:%(message)s

[logger_root]
level=DEBUG
handlers=consoleHandler,rotateFileHandler

[logger_example]
level=DEBUG
handlers=consoleHandler,rotateFileHandler
qualname=example
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[handler_rotateFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=('test.log','a',200000,9)





注意,RotatingFileHandler中doRollover()会因为rename()出错而中途退出,造成日志文件没有打开,并且后继的日志消息都因为日志文件没有打开而失败。可以自己在rename()处加上try,或者不用RotatingFileHandler。估计隔一段时间就fileConfig()一次也是可以恢复正常。
详见:Python logging RotatingFileHandler bug

该错误仅当日志文件满时切换文件时才可能发生,当文件被锁定时才会出错。正常使用不会有问题,并且日志出错不会影响主程序的运行。所以可以放心使用,想再可靠点就直接在源码中加个try.

(转载请注明来源于金庆的专栏)
页: [1]
查看完整版本: 使用Python的logging.config