python 日誌文件配置

自己搭建的日誌文件,日常使用可以滿足了

import datetime
import logging.handlers
import os
import logging
from logging.handlers import RotatingFileHandler

from init import log_dir

# 驗證日誌文件夾是否存在,不存在創建一個新的文件夾
def make_dir(make_dir_path):
    path = make_dir_path.strip()
    if not os.path.exists(path):
        os.makedirs(path)
    return path


def get_rotaing_handler(filename, log_level):
    if filename:
        handler = RotatingFileHandler(filename, maxBytes=1024 * 1024 * 100, backupCount=100, encoding="utf8")
    else:
        handler = RotatingFileHandler("./log.log", maxBytes=1024 * 1024 * 100, backupCount=100, encoding="utf8")
    formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d]- %(message)s")
    handler.setFormatter(formatter)
    handler.setLevel(log_level)
    return handler


def root_roating_handler(log_path, log_level):
    global _log_root_handler

    if (_log_root_handler is not None
            and _log_root_handler in logging.root.handlers):
        logging.root.removeHandler(_log_root_handler)

    logging.root.setLevel(logging.NOTSET)
    _log_root_handler = get_rotaing_handler(log_path, log_level)
    logging.root.addHandler(_log_root_handler)


_log_root_handler = None

if __name__ == '__main__':
	 # 日誌等級
    log_level = "INFO"
   	# 文件名
    log_file = "img" + datetime.datetime.now().strftime(".%Y%m%d.log")
    # 路徑
    log_path = os.path.join(log_dir, log_file)
     # 檢驗並創建路徑
    make_dir(log_dir)
    # 初始化logging
    root_roating_handler(log_path, log_level)
    
    logging.debug('debug message')  # 低級別的:排錯信息
    logging.info('debug message')  # 正常信息
    logging.warning('warning message')  # 警告信息
    logging.error('error message')  # 錯誤信息
    logging.critical('critical message')  # 高級別的  : 嚴重錯誤信息

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章