使用配制文件的方法,配制文件logging.conf的内容如下:
[handlers]
keys=fileHandler,consoleHandler [formatters] keys=fileFormatter,consoleFormatter [logger_root] level=DEBUG handlers=fileHandler [logger_fileExample] level=DEBUG handlers=fileHandler qualname=fileExample propagate=0 [handler_fileHandler] class=FileHandler level=DEBUG formatter=fileFormatter filemode='w' args=("myapp.log", "a") [logger_consoleExample] level=DEBUG handlers=consoleHandler qualname=consoleExample propagate=0 [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=consoleFormatter args=(sys.stdout,) [formatter_fileFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt= [formatter_consoleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt=
这个配制文件同时指明了输出到控制台和文件的参数。
测试代码如下:
import logging import logging.config logging.config.fileConfig('logging.conf') logger1 = logging.getLogger('fileExample') logger1.debug('debug message') logger2 = logging.getLogger('consoleExample') logger2.debug('debug message')
参考资料:
1.python官方文档https://docs.python.org/2/howto/logging.html#logging-advanced-tutorial
2.python 的日志logging模块学习 http://blog.csdn.net/yatere/article/details/6655445