文档: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. 数据结构--Dijkstra算法最清楚的讲解

    迪杰斯特拉(Dijkstra)算法是典型最短路径算法,用于计算一个节点到其他节点的最短路径.它的主要特点是以起始点为中心向外层层扩展(广度优先搜索思想),直到扩展到终点为止 ###基本思想 通过Dij ...

  2. WPF学习笔记二 依赖属性实现原理及性能分析

    在这里讨论依赖属性实现原理,目的只是学习WPF是怎么设计依赖属性的,同时更好的使用依赖属性. 首先我们来思考一个简单的问题:我们希望能验证属性的值是否有效,属性变更时进行自己的处理.回顾一下.net的 ...

  3. jQuery中ajax请求的六种方法(三、一):$.ajax()方法

    1.基础的$.ajax()方法 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"&g ...

  4. go语言 切片表达式

    切片表达式 切片的底层就是一个数组,所以我们可以基于数组通过切片表达式得到切片. 切片表达式中的low和high表示一个索引范围(左包含,右不包含),得到的切片长度=high-low,容量等于得到的切 ...

  5. linux shell 脚本输入参数解析

    文件名: test.sh #!/bin/bash para="para: "; while [ $# -ge 2 ] ; do case "$1" in --a ...

  6. Java线程池工作原理

    前言 当项目中有频繁创建线程的场景时,往往会用到线程池来提高效率.所以,线程池在项目开发过程中的出场率是很高的. 那线程池是怎么工作的呢?它什么时候创建线程对象,如何保证线程安全... 什么时候创建线 ...

  7. Linux centos7 find 命令

    2021-08-13 1. 命令简介 find 命令用来在指定目录下查找文件.任何位于参数之前的字符串都将被视为欲查找的目录名.如果使用该命令时,不设置任何参数,则 find 命令将在当前目录下查找子 ...

  8. Python学习笔记摘要(一)类型 字符串 函数 列表 深浅拷贝

    python中的对象和类型 在python中,认为系统中的每一个"东西"都是一个对象,在python中,"对象"有着特殊的意义,python中的对象有: 一个标 ...

  9. golang context包

    go context标准库 context包在Go1.7版本时加入到标准库中.其设计目标是给Golang提供一个标准接口来给其他任务发送取消信号和传递数据.其具体作用为: 可以通过context发送取 ...

  10. 第17章-x86-64寄存器

    不同的CPU都能够解释的机器语言的体系称为指令集架构(ISA,Instruction Set Architecture),也可以称为指令集(instruction set).Intel将x86系列CP ...