设为首页 加入收藏

TOP

Python logging模块详解(三)
2015-02-02 14:33:05 来源: 作者: 【 】 浏览:69
Tags:Python logging 模块 详解
CRITICAL - logger5 critical message
2014-05-06 15:32:10,762 - mylogger.child1.child2.child3 - CRITICAL - logger5 critical message
2014-05-06 15:32:10,762 - mylogger.child1.child2.child3 - CRITICAL - logger5 critical message

发现root、mylogger、mylogger.child1的输出全部被过滤掉了。


除了直接在程序中设置Logger,Handler,Filter,Formatter外还可以将这些信息写进配置文件中。


例如典型的logging.conf


[loggers]
keys=root,simpleExample


[handlers]
keys=consoleHandler


[formatters]
keys=simpleFormatter


[logger_root]
level=DEBUG
handlers=consoleHandler


[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0


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


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


程序可以这么写


import logging?
import logging.config?
?
logging.config.fileConfig("logging.conf")? ? # 采用配置文件?
?
# create logger?
logger = logging.getLogger("simpleExample")?
?
# "application" code?
logger.debug("debug message")?
logger.info("info message")?
logger.warn("warn message")?
logger.error("error message")?
logger.critical("critical message")


多模块使用logging
logging模块保证在同一个python解释器内,多次调用logging.getLogger('log_name')都会返回同一个logger实例,即使是在多个模块的情况下。所以典型的多模块场景下使用logging的方式是在main模块中配置logging,这个配置会作用于多个的子模块,然后在其他模块中直接通过getLogger获取Logger对象即可。

main.py:


import logging?
import logging.config?
?
logging.config.fileConfig('logging.conf')?
root_logger = logging.getLogger('root')?
root_logger.debug('test root logger...')?
?
logger = logging.getLogger('main')?
logger.info('test main logger')?
logger.info('start import module \'mod\'...')?
import mod?
?
logger.debug('let\'s test mod.testLogger()')?
mod.testLogger()?
?
root_logger.info('finish test...')


子模块mod.py:


import logging?
import submod?
?
logger = logging.getLogger('main.mod')?
logger.info('logger of mod say something...')?
?
def testLogger():?
? ? logger.debug('this is mod.testLogger...')?
? ? submod.tst()


子子模块submod.py:


import logging?
?
logger = logging.getLogger('main.mod.submod')?
logger.info('logger of submod say something...')?
?
def tst():?
? ? logger.info('this is submod.tst()...')?


首页 上一页 1 2 3 4 5 6 7 下一页 尾页 3/7/7
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Python内置的urllib模块不支持htt.. 下一篇让shell脚本中的echo输出带颜色

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: