python 的log格式

  • log.py
import logging
import logging.handlers
import os

def init_log(log_path, level=logging.INFO, when="D", backup=7,
             format='%(asctime)s:[%(levelname)s][%(threadName)s] %(filename)s:%(lineno)d --> %(message)s',
             datefmt='%Y-%m-%d %H:%M:%S'):
    """
    init_log - initialize log module

    Args:
      log_path      - Log file path prefix.
                      Log data will go to two files: log_path.log and log_path.log.wf
                      Any non-exist parent directories will be created automatically
      level         - msg above the level will be displayed
                      DEBUG < INFO < WARNING < ERROR < CRITICAL
                      the default value is logging.INFO
      when          - how to split the log file by time interval
                      'S' : Seconds
                      'M' : Minutes
                      'H' : Hours
                      'D' : Days
                      'W' : Week day
                      default value: 'D'
      format        - format of the log
                      default format:
                      %(levelname)s: %(asctime)s: %(filename)s:%(lineno)d * %(thread)d %(message)s
                      INFO: 12-09 18:02:42: log.py:40 * 139814749787872 HELLO WORLD
      backup        - how many backup file to keep
                      default value: 7

    Raises:
        OSError: fail to create log directories
        IOError: fail to open log file
    """
    formatter = logging.Formatter(format, datefmt)
    logger = logging.getLogger()
    logger.setLevel(level)

    # add console log
    consoleHandler = logging.StreamHandler()
    consoleHandler.setLevel(level)
    consoleHandler.setFormatter(formatter)
    logger.addHandler(consoleHandler)
        
    log_dir = os.path.dirname(log_path)
    if not os.path.isdir(log_dir):
        os.makedirs(log_dir)

    handler = logging.handlers.TimedRotatingFileHandler(log_path + '.log',
                                                        when=when,
                                                        backupCount=backup)
    handler.setLevel(level)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
  • 你可以把上面的代码拷贝到自己的项目中。在程序初始化时,调用init_log即可使日志打印符合规范
import log
def main():
    log.init_log("./log/my_program")  # 日志保存到./log/my_program.log和./log/my_program.log.wf,按天切割,保留7天
    logging.info("Hello World!!!")

参考

*logging — Logging facility for Python

猜你喜欢

转载自kanpiaoxue.iteye.com/blog/2215010