1. 程式人生 > >python 基礎logging模組自定義封裝,同時輸出到本地資料夾以及python控制檯

python 基礎logging模組自定義封裝,同時輸出到本地資料夾以及python控制檯

# coding=utf-8
import logging
import os
import time
import logging.handlers


class TestLogger(object):
    def __init__(self, log_dir_path):
        # logs 檔案父目錄
        self.log_dir_path = log_dir_path
        if os.path.exists(log_dir_path) and os.path.isdir(log_dir_path):
            pass
        else:
            os.mkdir(log_dir_path)
        time_stamp_name = time.strftime("%Y%m%d%H%M%S%a", time.localtime())
        log_name = time_stamp_name + ".log"
        # logs 檔案路徑
        self.log_path = os.path.join(log_dir_path, log_name)
        # logs 檔案輸出格式
        self.log_format = "[%(asctime)s] The location of the file output by the log:%(pathname)s \nThe name of the " \
            "module generated under the current file is named: %(funcName)s,The specific number of lines " \
            "corresponding to the file is line %(lineno)d,\nCorresponding log level is :[%(levelname)s]:%(message)s"
        self.date_format = "%Y-%m-%d %H:%M:%S %a"

        """logs在檔案輸出格式控制"""
        logging.basicConfig(level=logging.DEBUG,
                            format=self.log_format,
                            datefmt=self.date_format,
                            filename=self.log_path)

        """logs檔案內容轉換控制檯輸出,檔案處理器處理"""

        rotating_file_handler = logging.handlers.RotatingFileHandler(filename=self.log_path,
                                                                     maxBytes=1024 * 1024 * 50,
                                                                     backupCount=5)
        rotating_file_handler.setFormatter(self.log_format)

        """python控制檯控制代碼設定輸出日誌格式"""
        self.console = logging.StreamHandler()
        self.console.setLevel(logging.NOTSET)
        self.console_format = logging.Formatter(self.log_format)
        self.console.setFormatter(self.console_format)

    """新增日誌content到控制代碼並返回新增完成的控制代碼 """
    def console_log(self):
        logger = logging.getLogger()
        logger.addHandler(self.console)
        logger.setLevel(logging.DEBUG)
        return logger

if name == “main”: logs = TestLogger(r"d:\test").console_log() logs.info(“111000”) logs.warning(“war_start”) logs.critical(“criminal”) logs.error(“error00001”)

效果如下: 在這裡插入圖片描述