python日志loguru


文檔:https://loguru.readthedocs.io/en/stable/overview.html#installation

pip install loguru

使用

基本使用

##終端日志
from loguru import logger
logger.debug("這是一條debug日志")


###輸出到文件
from loguru import logger

logger.add("file_{time}.log")

logger.debug("這是一條debug日志")
logger.info("這是一條info日志")

##日志規則
#logger.add("file.log", format="{time} {level} {message}", filter="", level="INFO")

#默認的輸出格式是上面的內容,有時間、級別、模塊名、行號以及日志信息

logger.add(f"{log_path}/log{t}.log", rotation="500MB", encoding="utf-8", enqueue=True,
               format="{time:YYYY-MM-DD HH:mm:ss} |  {name} | {line} | {message}", retention="10 days")

#這個格式比較好
logger.add("file.log", format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}")
2020-06-24 at 20:49:04 | INFO | hehhehejhjkfffffffffffff--------->>>jhgfdhjkdj----------<>jh
2020-06-24 at 20:49:15 | INFO | jfsdghdjkhf

logger.debug("這是一條debug日志")
logger.info("這是一條info日志")


##add方法
def add(
    self,
    sink,
    *,
    level=_defaults.LOGURU_LEVEL,
    format=_defaults.LOGURU_FORMAT,
    filter=_defaults.LOGURU_FILTER,
    colorize=_defaults.LOGURU_COLORIZE,
    serialize=_defaults.LOGURU_SERIALIZE,
    backtrace=_defaults.LOGURU_BACKTRACE,
    diagnose=_defaults.LOGURU_DIAGNOSE,
    enqueue=_defaults.LOGURU_ENQUEUE,
    catch=_defaults.LOGURU_CATCH,
    **kwargs
):
    r"""Add a handler sending log messages to a sink adequately configured.


sink 可以傳入一個 file 對象,例如 sys.stderr 或者 open('file.log', 'w') 都可以。
sink 可以直接傳入一個 str 字符串或者 pathlib.Path 對象,其實就是代表文件路徑的,如果識別到是這種類型,它會自動創建對應路徑的日志文件並將日志輸出進去。
sink 可以是一個方法,可以自行定義輸出實現。
sink 可以是一個 logging 模塊的 Handler,比如 FileHandler、StreamHandler 等等,或者上文中我們提到的 CMRESHandler 照樣也是可以的,這樣就可以實現自定義 Handler 的配置。
sink 還可以是一個自定義的類,具體的實現規范可以參見官方文檔。

刪除 sink:

from loguru import logger
 
trace = logger.add('runtime.log')  ##獲取返回值
logger.debug('this is a debug message')
logger.remove(trace)  ##刪除舊的日志文件
logger.debug('this is another debug message')

日志文件管理方式

logger.add("file_1.log", rotation="500 MB")    # 文件過大就會重新生成一個文件
logger.add("file_2.log", rotation="12:00")     # 每天12點創建新文件
logger.add("file_3.log", rotation="1 week")    # 文件時間過長就會創建新文件

logger.add("file_X.log", retention="10 days")  # 一段時間后會清空

logger.add("file_Y.log", compression="zip")    # 保存zip格式

logger.add('runtime_{time}.log', rotation='1 week')

##輸出字符串格式化
logger.info('If you are using Python {}, prefer {feature} of course!', 3.6, feature='f-strings')

n1 = "cool"
n2 = [1, 2, 3]
logger.info(f'If you are using Python {n1}, prefer {n2} of course!')

其他參數

logger.add("somefile.log", enqueue=True)  # 異步寫入

logger.add("somefile.log", serialize=True)  # 序列化為json

創建多個文件處理器對象並解決中文亂碼問題

# coding=utf-8
import os
import sys
from loguru import logger

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

log_file_path = os.path.join(BASE_DIR, 'Log/my.log')
err_log_file_path = os.path.join(BASE_DIR, 'Log/err.log')

logger.add(sys.stderr, format="{time} {level} {message}", filter="my_module", level="INFO")
# logger.add(s)
logger.add(log_file_path, rotation="500 MB", encoding='utf-8')  # Automatically rotate too big file
logger.add(err_log_file_path, rotation="500 MB", encoding='utf-8',
           level='ERROR')  # Automatically rotate too big file
logger.debug("That's it, beautiful and simple logging!")
logger.debug("中文日志可以不")
logger.error("嚴重錯誤")

字符串格式化

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

裝飾器

@logger.catch
def my_function(x, y, z):
    # An error? It's caught anyway!
    return 1 / (x + y + z)


單獨的日志模塊工具

項目路徑下的util文件夾之類的,不能直接放項目路徑下,不然路徑會生成錯誤

"""
操作日志記錄
"""
import time
from loguru import logger
from pathlib import Path
 
project_path = Path.cwd().parent       ##獲取當前模塊文件所在目錄的上一層
log_path = Path(project_path, "log")   ##產生日志目錄字符串
t = time.strftime("%Y_%m_%d")          ##2020_06_24
 
class Loggings:
    __instance = None
    logger.add(f"{log_path}/interface_log_{t}.log", rotation="500MB", encoding="utf-8", enqueue=True,
               retention="10 days")
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(Loggings, cls).__new__(cls, *args, **kwargs)
 
        return cls.__instance
 
    def info(self, msg):
        return logger.info(msg)
 
    def debug(self, msg):
        return logger.debug(msg)
 
    def warning(self, msg):
        return logger.warning(msg)
 
    def error(self, msg):
        return logger.error(msg)
 
loggings = Loggings()
if __name__ == '__main__':
    loggings.info("中文test")
    loggings.debug("中文test")
    loggings.warning("中文test")
    loggings.error("中文test")
 
    logger.info('If you are using Python {}, prefer {feature} of course!', 3.6, feature='f-strings')
    n1 = "cool"
    n2 = [1, 2, 3]
    logger.info(f'If you are using Python {n1}, prefer {n2} of course!')

項目里loguru使用

根據催慶才的項目,還有一種用法
在項目的根目錄下創建setting文件並使用

logger.add(env.str('LOG_RUNTIME_FILE', 'runtime.log'), level='DEBUG', rotation='1 week', retention='20 days')
logger.add(env.str('LOG_ERROR_FILE', 'error.log'), level='ERROR', rotation='1 week')

初步實驗了一下


import os
import time
from loguru import logger

basedir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# print(f"log basedir{basedir}")  # /xxx/python_code/FastAdmin/backend/app
# 定位到log日志文件
log_path = os.path.join(basedir, 'logs')

if not os.path.exists(log_path):
    os.mkdir(log_path)

log_path_error = os.path.join(log_path, f'{time.strftime("%Y-%m-%d")}_error.log')

# 日志簡單配置
# 具體其他配置 可自行參考 https://github.com/Delgan/loguru
logger.add(log_path_error, rotation="12:00", retention="5 days", enqueue=True)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM