python logging 备忘

常用format

log_formatter = logging.Formatter("%(asctime)s %(process)s %(thread)s %(filename)s [%(levelname)-5.5s] %(message)s")

常用handler

  1. TimedRotatingFileHandler 按照日期切分日志

    如下:

    from logging.handlers import TimedRotatingFileHandler
    file_handler = TimedRotatingFileHandler('%smain.log' % log_path, when='midnight')
    file_handler.suffix = '%Y_%m_%d.log'
    file_handler.setFormatter(log_formatter)            
    
  2. StreamHandler std输出

    如下:

     std_handler = logging.StreamHandler(sys.stdout)
     std_handler.setFormatter(log_formatter)
     

添加handler

logger = logging.getLogger()
logger.addHandler(file_handler)
logger.addHandler(std_handler)
logger.setLevel(logging.WARNING)


終わり。

本文固定链接:

python-logging备忘

http://www.js-code.com/python/python_51017.html

80%的人都看过