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中記錄追蹤信息。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章