文档: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)

python日志loguru的更多相关文章

  1. 异步日志 Loguru

    https://mp.weixin.qq.com/s/hy68s610B9GbL_wgwTn7nA 更优美的python日志管理库Loguru Asynchronous, Thread-safe, M ...

  2. Python日志输出——logging模块

    Python日志输出——logging模块 标签: loggingpythonimportmodulelog4j 2012-03-06 00:18 31605人阅读 评论(8) 收藏 举报 分类: P ...

  3. python日志模块logging

    python日志模块logging   1. 基础用法 python提供了一个标准的日志接口,就是logging模块.日志级别有DEBUG.INFO.WARNING.ERROR.CRITICAL五种( ...

  4. 浅析python日志重复输出问题

    浅析python日志重复输出问题 问题起源: ​ 在学习了python的函数式编程后,又接触到了logging这样一个强大的日志模块.为了减少重复代码,应该不少同学和我一样便迫不及待的写了一个自己的日 ...

  5. python 日志打印之logging使用介绍

    python 日志打印之logging使用介绍 by:授客QQ:1033553122 测试环境: Python版本:Python 2.7   简单的将日志打印到屏幕 import logging lo ...

  6. python 日志的配置,python对日志封装成类,日志的调用

    # python 日志的配置,python对日志封装成类,日志的调用 import logging # 使用logging模块: class CLog: # --------------------- ...

  7. python日志模块logging学习

    介绍 Python本身带有logging模块,其默认支持直接输出到控制台(屏幕),或者通过配置输出到文件中.同时支持TCP.HTTP.GET/POST.SMTP.Socket等协议,将日志信息发送到网 ...

  8. Python 日志输出中添加上下文信息

    Python日志输出中添加上下文信息 除了传递给日志记录函数的参数(如msg)外,有时候我们还想在日志输出中包含一些额外的上下文信息.比如,在一个网络应用中,可能希望在日志中记录客户端的特定信息,如: ...

  9. python日志模块笔记

    前言 在应用中记录日志是程序开发的重要一环,也是调试的重要工具.但却很容易让人忽略.之前用flask写的一个服务就因为没有处理好日志的问题导致线上的错误难以察觉,修复错误的定位也很困难.最近恰好有时间 ...

随机推荐

  1. NOIP 模拟 $25\; \rm queen$

    题解 \(by\;zj\varphi\) 这是一道纯分类讨论,然后推式子的题,细节挺多,挺麻烦,但是很考验数学能力 不讲了,官方题解给的很清楚 Code: %: pragma GCC optimize ...

  2. 题解 Merchant

    传送门 可以发现如果我们最终选择的物品集合已经确定,就很好求了 \(\sum k*t+\sum b \geqslant s\) ,二分即可 但现在我们无法确定该选哪些物品 因此我们只需要check一下 ...

  3. Spring详解(四)------注解配置DI

    第一步:在 applicationContext.xml 中引入命名空间 这里我们简单讲解一下这里引入的命名空间,简单来说就是用来约束xml文件格式的.第一个 xmlns:context ,这表示标签 ...

  4. C# 串口开发

    在单片机项目开发中,上位机也是一个很重要的部分,主要用于数据显示(波形.温度等).用户控制(LED,继电器等),下位机(单片机)与 上位机之间要进行数据通信的两种方式都是基于串口的: USB转串口 - ...

  5. java基本数据类型转换字符串

    1.基本数据类型转换为字符串 int t1 = 2; String t2 = Integer.toString(t1); 2.字符串转换为基本数据类型 int t3 = Integer.parseIn ...

  6. OpenCV waitKey 无法正常捕捉方向键(上下左右),总结和解决方案,可以用waitKeyEx

    在win10+python+opencv3.4.5,测试 while True: key = cv2.waitKey(0) print('key =', key) 依次按上.下.左.右方向键,输出: ...

  7. 学习小记: Kaggle Learn - Machine Learning Explainability

    Method Feature(s) Sample(s) Result Value/Feature Permutation Importance 1 all validation samples Sin ...

  8. yum命令报错File "/usr/bin/yum", line 30 except KeyboardInterrupt, e:

    使用yum命令报错File "/usr/bin/yum", line 30 except KeyboardInterrupt, e: 问题出现原因:yum包管理是使用python2 ...

  9. 5M1E,软件质量管理最佳解决方案

    - 如何做好一个产品? - 用户.需求.文化.价值.设计.流程,这些因素缺一不可.- 那么,如何做好产品的质量管理?- 人.机器.物料.方法.环境.测量,这些因素同样缺一不可.能够影响产品质量波动的因 ...

  10. 剑指 Offer 36. 二叉搜索树与双向链表

    剑指 Offer 36. 二叉搜索树与双向链表 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表.要求不能创建任何新的节点,只能调整树中节点指针的指向. 为了让您更好地理解问题,以下面的 ...