一、代码
通用日志记录器,可以输出不同颜色的记录到控制台,并输出到指定文件夹下 可以在不同py文件中同时使用,共用同一个记录器 适用window或linux平台
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import inspect
import logging
import platform
from pathlib import Path
from colorlog import ColoredFormatter
from logging.handlers import RotatingFileHandler
RES_LOG_PATH = "要输出的log文件目录"
def log(name: str = None) -> logging.Logger:
"""
设置并返回到记录器
:param name: 记录器名字
:return: 记录器
"""
# 重置根记录器处理程序
root_logger = logging.getLogger()
root_logger.handlers = []
if not name:
absolute_path = Path(inspect.stack()[1].filename).resolve()
relative_path = str(absolute_path.relative_to(Path(__file__).resolve().parent.parent))
spliter = (
lambda sys: "\\" if sys == "Windows" else "/" if sys == "Linux" else Exception("Incompatible systems"))(
platform.system())
name = ".".join([str(n) for n in os.path.splitext(relative_path)[0].split(spliter) if n])
# 检查记录器是否存在,如果存在则返回,否则创建
logger = logging.getLogger(name)
if logger.hasHandlers():
return logger
else:
# 创建记录器对象
logger = logging.getLogger(str(name.split(".")[0]))
logger.setLevel(logging.DEBUG)
# 定义 Handler 对象
file_handler = RotatingFileHandler(RES_LOG_PATH, maxBytes=1048576, backupCount=10,encoding="utf-8")
console_handler = logging.StreamHandler()
# 设置日志级别
file_handler.setLevel(logging.DEBUG)
console_handler.setLevel(logging.DEBUG)
# 设置输出格式化程序
file_fmt = "%(asctime)s %(levelname)s [%(name)s] %(message)s"
color_fmt = f"%(log_color)s{file_fmt}%(reset)s"
date_fmt = "%Y-%m-%d %H:%M:%S"
file_formatter = logging.Formatter(file_fmt)
console_formatter = ColoredFormatter(
color_fmt, datefmt=date_fmt, reset=True,
log_colors={
"DEBUG": "cyan", "INFO": "green",
"WARNING": "yellow", "ERROR": "red",
"CRITICAL": "red",
},
)
file_handler.setFormatter(file_formatter)
console_handler.setFormatter(console_formatter)
# 将处理程序添加到记录器
logger.addHandler(file_handler)
logger.addHandler(console_handler)
logger.info(f"Initialize logger {name}")
return logging.getLogger(name)
二、使用
1、在代码中使用
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from logger import log
logger = log()
logger.info("this is a info")
logger.debug("this is a debug")
logger.warning("this is a warning")
logger.error("this is a error")
2、输出
(1)控制台
(2)文件