当前位置:   article > 正文

Python logging浅尝(将log同时输出到Console和日志文件)_python logging console

python logging console

先贴上logger/handler/formatter/filter的用处(来源见参考中链接):
Loggers expose the interface that application code directly uses.
Handlers send the log records (created by loggers) to the appropriate destination.
Filters provide a finer grained facility for determining which log records to output.
Formatters specify the layout of log records in the final output.

logging.basicConfig() --日志配置的快速方法

配置日志的方便快捷的方法,支持将log输出到控制台(Console)或文件中,但只支持一种。用法如下:

import logging

logging.basicConfig(filename='test.log', level=logging.DEBUG)
logging.info('this is info log')
  • 1
  • 2
  • 3
  • 4

basicConfig(**kwargs)代码长这个样子:

root = RootLogger(WARNING)
Logger.root = root
Logger.manager = Manager(Logger.root)

def basicConfig(**kwargs):
    # Add thread safety in case someone mistakenly calls
    # basicConfig() from multiple threads
    _acquireLock()
    try:
        if len(root.handlers) == 0:
            filename = kwargs.get("filename")
            if filename:
                mode = kwargs.get("filemode", 'a')
                hdlr = FileHandler(filename, mode)
            else:
                stream = kwargs.get("stream")
                hdlr = StreamHandler(stream)
            fs = kwargs.get("format", BASIC_FORMAT)
            dfs = kwargs.get("datefmt", None)
            fmt = Formatter(fs, dfs)
            hdlr.setFormatter(fmt)
            root.addHandler(hdlr)
            level = kwargs.get("level")
            if level is not None:
                root.setLevel(level)
    finally:
        _releaseLock()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

可以看到,是先根据传入的内容,创建了logger(root),又创建了相应的handler(FileHandler和StreamHandler,前者输入log到文件,后者输入到console),并为已创建的的handler设置格式(hdlr.setFormatter(fmt)),然后将创建的handler加入到logger中(root.addHandler(hdlr)),最后为logger设置日志级别(root.setLevel(level))。
由上可见basicConfig()是将日志配置的一些方法封装了起来。

日志配置的一般方法(logger→handler)

下面的例子实现将log同时输出到Console和日志文件,思路参考basicConfig():

import logging

logger = logging.getLogger()
logger.setLevel('DEBUG')
BASIC_FORMAT = "%(asctime)s:%(levelname)s:%(message)s"
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
chlr = logging.StreamHandler() # 输出到控制台的handler
chlr.setFormatter(formatter)
chlr.setLevel('INFO')  # 也可以不设置,不设置就默认用logger的level
fhlr = logging.FileHandler('example.log') # 输出到文件的handler
fhlr.setFormatter(formatter)
logger.addHandler(chlr)
logger.addHandler(fhlr)
logger.info('this is info')
logger.debug('this is debug')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

运行的结果:

# 控制台
2018-03-07 11:08:54:INFO:this is info
  • 1
  • 2
# example.log
2018-03-07 11:08:54:INFO:this is info
2018-03-07 11:08:54:DEBUG:this is debug
  • 1
  • 2
  • 3

附上:日志级别

levelNumeric value
critical50
error40
warning30
info20
debug10
notset0

举例:目前日志级别设置为INFO,则除了DEBUG的日志不会打印外,其他的都会打印出来。

参考:
https://docs.python.org/3/library/logging.html
https://docs.python.org/3/howto/logging.html#logging-basic-tutorial

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/815961
推荐阅读
相关标签
  

闽ICP备14008679号