loguru日志使用


loguru日志方案

  • 日志相关内容:
    • 目志输出渠道: 文件,控制台输出
    • 日志级别: DEBUG < INFO < WARNING < ERROR < CRITICAL
    • 日志内容: 年月日、时分秒、级别、哪行代码报错、具休报错
  • 日的注意事项:
    • 日志文件不能太大:切割日志,按照指定大小200kb,按照指定时间等
    • 项目日志特别多, 会占服务器空间一一是否可以压缩zip 一一200k 变成1@k
    • 定期清理日志

1 安装

pip install loguru

2 控制台输出

from loguru import logger

logger.debug("That's it, beautiful and simple logging!")
logger.info("That's it, beautiful and simple logging!")
logger.warning("That's it, beautiful and simple logging!")
logger.error("That's it, beautiful and simple logging!") 
logger.critical("That's it, beautiful and simple logging!")

3 文件输出

自定义输出文件格式:

add(sink, *, 
    level='DEBUG', 
    format='<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>', 
    filter=None, 
    colorize=None, 
    serialize=False, 
    backtrace=True, diagnose=True, enqueue=False, catch=True, **kwargs)

参数说明

  • sink:支持多种数据结构,可以传入一个字符串、一个文件对象、一个路径对象代表路径、一个方法、logging模块的Handler
  • level:默认为debug类型
  • format:输出格式设置
  • encoding:编码格式设置

代码案例1:

import pathlib
from loguru import logger

# 日志存储目录
log_dir = pathlib.Path('./logs')
log_dir.mkdir(exist_ok=True)

log_file = log_dir.joinpath('loguru_{time: YYYY_MM_DD}.log')

# 移除控制台输出
logger.remove(handler_id=None)
# 添加文件记录器, 指定文件大小,文件达到指定文件大小时,压缩log日志文件
logger.add(log_file, rotation='200kb', compression='zip')

logger.debug("That's it, beautiful and simple logging!")
logger.info("That's it, beautiful and simple logging!")
logger.warning("That's it, beautiful and simple logging!")
logger.error("That's it, beautiful and simple logging!")
logger.critical("That's it, beautiful and simple logging!")

输入到文件中内容如下:

代码案例2:

# -*- coding: UTF-8 -*-
import pathlib
from loguru import logger

# 日志存储目录
log_dir = pathlib.Path('./logs')
log_dir.mkdir(exist_ok=True)

log_file = log_dir.joinpath('loguru_{time: YYYY_MM_DD}.log')

# 添加文件记录器, 指定文件大小,文件达到指定文件大小时,压缩log日志文件, 指定编码格式
logger.add(log_file, rotation='200kb', compression='zip', encoding='utf-8')


def div(a, b):
    return a / b

try:
    div(2, 0)
except Exception as e:
    logger.error('分母不能为0')

4 配置

4.1 roation配置

设置创建新的日志文件的条件

  • 按照文件大小输出日志

    # 日志超过500MB就会新建一个log日志文件
    logger.add('runtime_{time}.log', rotation="500 MB")
    
  • 按照时间输出日志

    # 设置每天零点创建一个日志文件
    logger.add('runtime_{time}.log', rotation='00:00')
    # 设置每隔一周创建一个日志文件
    logger.add('runtime_{time}.log', rotation='1 week')
    

**rotation参数说明: **

- an |int| which corresponds to the maximum file size in bytes before that the current
  logged file is closed and a new one started over.
- a |timedelta| which indicates the frequency of each new rotation.
- a |time| which specifies the hour when the daily rotation should occur.
- a |str| for human-friendly parametrization of one of the previously enumerated types.
  Examples: ``"100 MB"``, ``"0.5 GB"``, ``"1 month 2 weeks"``, ``"4 days"``, ``"10h"``,
  ``"monthly"``, ``"18:00"``, ``"sunday"``, ``"w0"``, ``"monday at 12:00"``, ...
- a |function|_ which will be called before logging. It should accept two
  arguments: the logged message and the file object, and it should return ``True`` if
  the rotation should happen now, ``False`` otherwise.

4.2 retention 配置

设置日志文件的保留时间

logger.add('runtime.log', retention='10 days')

**retention 参数说明: **

- an |int| which indicates the number of log files to keep, while older files are removed.
- a |timedelta| which specifies the maximum age of files to keep.
- a |str| for human-friendly parametrization of the maximum age of files to keep.
  Examples: ``"1 week, 3 days"``, ``"2 months"``, ...
- a |function|_ which will be called before the retention process. It should accept the list
  of log files as argument and process to whatever it wants (moving files, removing them,
  etc.).

4.3 compression 配置

loguru 还可以配置文件的压缩格式,比如使用 zip 文件格式保存,示例如下:

logger.add('runtime.log', compression='zip')

compression 参数说明:

- a |str| which corresponds to the compressed or archived file extension. This can be one
  of: ``"gz"``, ``"bz2"``, ``"xz"``, ``"lzma"``, ``"tar"``, ``"tar.gz"``, ``"tar.bz2"``,
  ``"tar.xz"``, ``"zip"``.
- a |function|_ which will be called before file termination. It should accept the path
  of the log file as argument and process to whatever it wants (custom compression,
  network sending, removing it, etc.).

4.4 字符串格式化

loguru 在输出 log 的时候还提供了非常友好的字符串格式化功能

logger.info('If you are using Python {}, prefer {feature} of course!', 3.6, feature='f-strings')

输出结果:

2022-01-18 11:55:12.112 | INFO     | __main__:<module>:21 - If you are using Python 3.6, prefer f-strings of course!

5 Traceback 记录

使用装饰器,直接在函数或类前面加上@logger.catch

# -*- coding: UTF-8 -*-
import pathlib
from loguru import logger

# 日志存储目录
log_dir = pathlib.Path('./logs')
log_dir.mkdir(exist_ok=True)

log_file = log_dir.joinpath('loguru_{time: YYYY_MM_DD}.log')

# 添加文件记录器, 指定文件大小,文件达到指定文件大小时,压缩log日志文件
logger.add(log_file, rotation='200kb', compression='zip', encoding='utf-8')

@logger.catch
def div(a, b):
    return a / b

div(2, 0)

# try:
#     div(2, 0)
# except Exception as e:
#     logger.error('分母不能为0')

运行完毕,会在log中记录追踪信息。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM