Python日志 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()

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值