python loguru 日志模块

"""
sink 日志保存地方

level 发送到接收器的最低严重级别
级别    值    方法
TRACE   5   logger.trace()
DEBUG   10  logger.debug()
INFO    20  logger.info()
SUCCESS 25  logger.success()
WARNING 30  logger.warning()
ERROR   40  logger.error()
CRITICAL    50  logger.critical()

format 格式化模版
Key 官方描述    备注
elapsed The time elapsed since the start of the program     日期
exception  The formatted exception if any, none otherwise   
extra   The dict of attributes bound by the user (see bind())
file    The file where the logging call was made    出错文件
function    The function from which the logging call was made   出错方法
level   The severity used to log the message    日志级别
line    The line number in the source code  行数
message The logged message (not yet formatted)  信息
module  The module where the logging call was made  模块
name  The __name__ where the logging call was made  __name__
process The process in which the logging call was made  进程id或者进程名,默认是id
thread  The thread in which the logging call was made  线程id或者进程名,默认是id
time    The aware local time when the logging call was made 日期

filter 过滤器,决定消息是否发送到接收器
colorize 是否加颜色
serialize (bool, optional) 是否转换为json字符串
backtrace (bool, optional) 是否显示错误的完整堆栈跟踪
diagnostic (bool, optional) 生产中用False,避免敏感数据泄漏
enqueue (bool, optional) 多进程安全队列
catch (bool, optional) 错误是否自动捕获

rotation (str, int, datetime.time, datetime.timedelta or callable, optional) 配置日志切割
"100 MB""0.5 GB""1 month 2 weeks""4 days""10h""monthly" “4s” "18:00""sunday""w0""monday at 12:00"

Retention (str, int, datetime.timedelta or callable, optional) - 过滤在轮换或程序结束时应删除的旧文件的指令
"1 week, 3 days""2 months" "1 min"

compression (str or callable, optional) – 日志文件在关闭时转换成的压缩或归档格式
"gz","bz2","xz","lzma","tar","tar.gz","tar.bz2", "tar.xz","zip"

delay (bool, optional) – 文件是否应该在配置接收器后立即创建,或者延迟到第一个记录的消息。它默认为假
mode (str, optional) -- 内置 open() 函数的打开模式。它默认为“a”(以附加模式打开文件)
buffering (int, optional) -- 内置 open() 函数的缓冲策略。它默认为 1(行缓冲文件)
encoding (str, optional) -- 内置 open() 函数的文件编码。如果没有,它默认为 locale.getpreferredencoding()。

"""


"""
根据大小和时间轮换日志文件
import datetime
 
class Rotator:
 
    def __init__(self, *, size, at):
        now = datetime.datetime.now()
 
        self._size_limit = size
        self._time_limit = now.replace(hour=at.hour, minute=at.minute, second=at.second)
 
        if now >= self._time_limit:
            # The current time is already past the target time so it would rotate already.
            # Add one day to prevent an immediate rotation.
            self._time_limit += datetime.timedelta(days=1)
 
    def should_rotate(self, message, file):
        file.seek(0, 2)
        if file.tell() + len(message) > self._size_limit:
            return True
        if message.record["time"].timestamp() > self._time_limit.timestamp():
            self._time_limit += datetime.timedelta(days=1)
            return True
        return False
 
# Rotate file if over 500 MB or at midnight every day
rotator = Rotator(size=5e+8, at=datetime.time(4, 0, 0)) --# size单位是byte at里面填时分秒
logger.add("file.log", rotation=rotator.should_rotate)
"""
import time
from loguru import logger
def setup_log(logpath):
    logger.remove()
    format_info = "{time:YYYY-MM-DD at HH:mm:ss} {level} {message}"
    logger.add(logpath,format=format_info,level="DEBUG",rotation='23:59',compression="tar.gz",retention="30 days",encoding='utf-8')
    return logger

while True:
    file_name1 =  "" 
    logger1 = setup_log(file_name1)
    logger1.info("文件1测试")
    file_name2 =  ""
    logger2 = setup_log(file_name2)
    logger2.info("文件2测试")
    time.sleep(10)

你可能感兴趣的:(python,开发语言)