Python日志 loguru输出日志
loguru使用
·
log_utils.py
# -*- coding: utf-8 -*-
import os
import sys
from time import strftime, localtime
from loguru import logger
class LogUtils:
log_file_root_path = ""
@classmethod
def init_logger(cls, name, console_level='DEBUG', write_level='INFO'):
console_log_level_list = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
if console_level.upper() not in console_log_level_list:
raise Exception(f'控制台log设置的等级不存在,控制台log等级为:{console_log_level_list}')
write_log_level_list = ['DEBUG', 'INFO', 'WARNING']
if write_level.upper() not in write_log_level_list:
raise Exception(f'写入log设置的等级不存在,写入log等级为:{write_log_level_list}')
base_path, file_name = os.path.split(os.path.abspath(sys.argv[0]))
current_year_month_day = strftime('%Y%m%d', localtime())
current_hour_minute_second = strftime('%H%M%S', localtime())
log_base_path = os.path.join(base_path, f'logs/{current_year_month_day}')
if not os.path.exists(log_base_path):
os.makedirs(log_base_path)
cls.log_file_root_path = os.path.join(log_base_path,
f'{name}_{current_year_month_day}_{current_hour_minute_second}')
error_log_file_path = f'{cls.log_file_root_path}_error'
critical_log_file_path = f'{cls.log_file_root_path}_critical'
logger.remove() # 删除原来的样式
# 设置控制台打印不同颜色的log
logger.level('DEBUG', color='<blue>')
logger.level('INFO', color='<green>')
logger.level('WARNING', color='<yellow>')
logger.level('ERROR', color='<red>')
logger.level('CRITICAL', color='<magenta>')
# 控制台输出
logger.add(
sink=sys.stderr,
# 注意需要加上level标签,才能根据上面的配置显示不同的颜色
format='<level>{time:YYYY-MM-DD HH:mm:ss.SSS} [{level}] {message}(in: {file} line: {line})</level>',
level=console_level, # 设置log的level等级
colorize=True, # 开启颜色
)
# 记录设置writer_level (DEBUG INFO WARNING) 及其以上的等级全量log
logger.add(
sink=f'{cls.log_file_root_path}.log',
format='{time:YYYY-MM-DD HH:mm:ss.SSS} [{level}] {message}(in: {file} line: {line})',
rotation='50 MB', # 超过50MB就会重新生产一个文件(常用),其他用法可以查一下
filter=lambda x: x['level'].name in write_log_level_list, # 该文件里只写入 DEBUG INFO WARNING
encoding='utf-8',
compression='zip', # 压缩
level=write_level,
enqueue=True, # 开启异步
)
# 只记录error信息
logger.add(
sink=f'{error_log_file_path}.log',
format='{time:YYYY-MM-DD HH:mm:ss.SSS} [{level}] {message}(in: {file} line: {line})',
rotation='10 MB',
filter=lambda x: x['level'].name == 'ERROR', # 该文件里只写入 ERROR
encoding='utf-8',
level='ERROR',
enqueue=True, # 开启异步
)
# 只记录critical信息
logger.add(
sink=f'{critical_log_file_path}.log',
format='{time:YYYY-MM-DD HH:mm:ss.SSS} [{level}] {message}(in: {file} line: {line})',
rotation='10 MB',
filter=lambda x: x['level'].name == 'CRITICAL', # 该文件里只写入 CRITICAL
encoding='utf-8',
level='CRITICAL',
enqueue=True, # 开启异步
)
@classmethod
def get_logger(cls, name="default"):
new_log_file_path = f'{cls.log_file_root_path}_{name}'
new_logger = logger.bind(type=name)
new_logger.add(
sink=f'{new_log_file_path}.log',
format='{time:YYYY-MM-DD HH:mm:ss.SSS} [{level}] {message}(in: {file} line: {line})',
rotation='10 MB',
filter=lambda record: record.get("extra", dict()).get("type", "") == name,
encoding='utf-8',
enqueue=True, # 开启异步
compression='zip', # 压缩
)
return new_logger
test_log.py
# -*- coding: utf-8 -*-
from loguru import logger
from log_utils import LogUtils
LogUtils.init_logger("zby")
chat1_logger = LogUtils.get_logger("chat1")
chat2_logger = LogUtils.get_logger("chat2")
chat1_logger.info("Hello World11111111")
chat2_logger.info("Hello World22222222")
@logger.catch # 自动抓错,把异常信息写入error文件里
def test_log():
logger.debug(1111111)
logger.info(222222)
logger.warning(333333)
logger.error(444444)
logger.critical(555555)
1 / 0
if __name__ == '__main__':
test_log()

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)