可以创建一个日志工具.py,代码如下
from loguru import logger
from pathlib import Path
import os
folder_ = Path(__file__).resolve().parent.parent.joinpath('logs') # 日志文件夹路径
prefix_ = "compute_"
rotation_ = "10 MB"
retention_ = "30 days"
encoding_ = "utf-8"
backtrace_ = True # 确定异常跟踪是否应该延伸到捕获错误的点之外,以便于调试。您应该在生产环境中将其设置为 False 以避免泄露敏感信息。
diagnose_ = True # 确定变量值是否应在异常跟踪中显示。在生产环境中应将其设置为 False,以避免泄露敏感信息。
# 格式里面添加了process和thread记录,方便查看多进程和线程程序
format_ = '<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> ' \
'| <magenta>{process}</magenta>:<yellow>{thread}</yellow> ' \
'| <cyan>{name}</cyan>:<cyan>{function}</cyan>:<yellow>{line}</yellow> - <level>{message}</level>'
# 这里面采用了层次式的日志记录方式,就是低级日志文件会记录比他高的所有级别日志,这样可以做到低等级日志最丰富,高级别日志更少更关键
# debug
# logger.add(os.path.join(folder_,(prefix_+debug.log")), level="DEBUG", backtrace=backtrace_, diagnose=diagnose_,
# format=format_, colorize=False,
# rotation=rotation_, retention=retention_, encoding=encoding_,
# filter=lambda record: record["level"].no >= logger.level("DEBUG").no)
# info
logger.add(os.path.join(folder_, (prefix_+"info.log")), level="INFO", backtrace=backtrace_, diagnose=diagnose_,
format=format_, colorize=False,
rotation=rotation_, retention=retention_, encoding=encoding_,
filter=lambda record: record["level"].no >= logger.level("INFO").no)
# warning
# logger.add(os.path.join(folder_,(prefix_+warning.log"), level="WARNING", backtrace=backtrace_, diagnose=diagnose_,
# format=format_, colorize=False,
# rotation=rotation_, retention=retention_, encoding=encoding_,
# filter=lambda record: record["level"].no >= logger.level("WARNING").no)
# error
logger.add(os.path.join(folder_, (prefix_+"error.log")), level="ERROR", backtrace=backtrace_, diagnose=diagnose_,
format=format_, colorize=False,
rotation=rotation_, retention=retention_, encoding=encoding_,
filter=lambda record: record["level"].no >= logger.level("ERROR").no)
# critical
# logger.add(os.path.join(folder_,(prefix_+critical.log")), level="CRITICAL", backtrace=backtrace_, diagnose=diagnose_,
# format=format_, colorize=False,
# rotation=rotation_, retention=retention_, encoding=encoding_,
# filter=lambda record: record["level"].no >= logger.level("CRITICAL").no)