python日志记录:输出至控制台同时存储至文件

文章目录

  • logging模块实现
  • sys.stdout实现

记录日志存储的两种方式,均可以实现在控制台输出并将日志记录至文件

logging模块实现

import os
import sys
import logging
import datetime
import logging.handlers as handlers

# 定义记录日志的函数
def log(log_path, level=logging.INFO, when="D", backup=7,
        format="[%(asctime)s] [%(levelname)s] - %(message)s (%(filename)s:%(lineno)d * %(thread)d)",
        datefmt="%Y-%m-%d %H:%M:%S.%f"):
    """
    log - print log

    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'
      backup        - how many backup file to keep
                      default value: 7
      format        - format of the log
                      default format:
                      "[%(asctime)s] [%(levelname)+5s] - %(message)s (%(filename)s:%(lineno)d * %(thread)d)"
                      [2022-08-11 18:02:42.991] [INFO] - HELLO WORLD (log.py:40 * 139814749787872)
      datefmt       - format of time
                      default format: "%Y-%m-%d %H:%M:%S.%f"

    Raises:
        OSError: fail to create log directories
        IOError: fail to open log file
    """
    # 创建一个记录日志的logger
    logger = logging.getLogger()
    logger.setLevel(level)

    # log存储地址前缀
    log_dir = os.path.dirname(log_path)
    if not os.path.isdir(log_dir):
        os.makedirs(log_dir)

    # 定义日志的输出格式
    formatter = logging.Formatter(format, datefmt)

    # 往文件中写日志
    # 1. 输出正常信息
    handler_info = logging.handlers.TimedRotatingFileHandler(log_path + ".log", when=when, backupCount=backup,
                                                             encoding="utf-8")
    handler_info.setLevel(level)
    handler_info.setFormatter(formatter)
    logger.addHandler(handler_info)

    # 2. 输出警告信息
    handler_warning = logging.handlers.TimedRotatingFileHandler(log_path + ".log.wf", when=when, backupCount=backup,
                                                                encoding="utf-8")
    handler_warning.setLevel(logging.WARNING)
    handler_warning.setFormatter(formatter)
    logger.addHandler(handler_warning)

    # 往控制台写日志(通过stream参数控制字体颜色)
    sh = logging.StreamHandler(stream=sys.stdout)
    sh.setFormatter(formatter)
    logger.addHandler(sh)


# 使用
if __name__ == "__main__":
    # 初始化日志存储路径
    log("日志文件存储路径/test_{}.log".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))))
    # 开始输出日志
    logging.info("test")

sys.stdout实现

参考:日志重定向到文件

import os
import sys
import datetime

# 定义log类
class Logger(object):
    """
    记录日志
    """

    def __init__(self, file_path):
        self.terminal = sys.stdout
        self.log = open(file_path, "a")

    def write(self, msg):
        """
        写日志
        @return:
        """
        self.terminal.write(msg)
        self.log.write(msg)

    def flush(self):
        pass

# 定义记录日志的函数
def record_log(file_path):
    """
    存储日志并在控制台输出
    @param file_path: 文件存储路径
    @return:
    """
    time_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    file_path = file_path + '/log_{}.log'.format(time_now)
    sys.stdout = Logger(file_path)
   
# 使用
if __name__ == "__main__":
	# 初始化日志记录
	record_log(file_path="日志文件存储路径")
	# 开始输出
	print("test")

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