python 日志打印

output some logs into console(screen) and some logs into a log file.
e.g. warning and higher logs need output into screen, and all logs dump into a logfile.

NOTE those:

  • mode : If mode is not specified, ‘a’ is used
    • ref: RotatingFileHandler
  • propagate: If this attribute evaluates to true, events logged to this logger will be passed to the handlers of higher level (ancestor) loggers, in addition to any handlers attached to this logger * ref logging.Logger.propagate

sample:

import logging 
import sys
import os

def setup_test_logging(logfile = None, console_min_level = logging.WARN, file_min_level = logging.DEBUG):
    """ setup logging for test, output logs on console (default logging.WARN) and logfile(default logging.DEBUG)"""
    if logfile is None:
        filename = os.path.basename(sys.argv[0]).replace('.py', '.log')
    else: 
        filename = logfile
    from logging.handlers import RotatingFileHandler
    handler = RotatingFileHandler(filename, mode='w', 
                                  maxBytes=1024*1024, backupCount=5, 
                                  encoding='utf-8')
    fmt = logging.Formatter(
        "%(asctime)s %(filename)s:%(lineno)d %(levelname)-8s %(message)s"
    )
    handler.setLevel(file_min_level)
    handler.setFormatter(fmt)
    
    console = logging.StreamHandler(stream=sys.stdout)
    console.setLevel(console_min_level)
    fmt = logging.Formatter(
        "%(asctime)s.%(msecs)03d %(filename)s:%(lineno)d %(levelname)-8s %(message)s", datefmt="%H:%M:%S"
    )
    console.setFormatter(fmt)
    logging.basicConfig(handlers=[handler, console], level=file_min_level)
    
    root = logging.getLogger()
    root.propagate = 0
    # use logger defined in test case, output all logs in ONE log file
    for name in logging.Logger.manager.loggerDict.keys():
        logger = logging.getLogger(name)
        logger.handlers = root.handlers
        logger.propagate = 0```

你可能感兴趣的:(python,python,logging)