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)
python日志loguru的更多相关文章
- 异步日志 Loguru
https://mp.weixin.qq.com/s/hy68s610B9GbL_wgwTn7nA 更优美的python日志管理库Loguru Asynchronous, Thread-safe, M ...
- Python日志输出——logging模块
Python日志输出——logging模块 标签: loggingpythonimportmodulelog4j 2012-03-06 00:18 31605人阅读 评论(8) 收藏 举报 分类: P ...
- python日志模块logging
python日志模块logging 1. 基础用法 python提供了一个标准的日志接口,就是logging模块.日志级别有DEBUG.INFO.WARNING.ERROR.CRITICAL五种( ...
- 浅析python日志重复输出问题
浅析python日志重复输出问题 问题起源: 在学习了python的函数式编程后,又接触到了logging这样一个强大的日志模块.为了减少重复代码,应该不少同学和我一样便迫不及待的写了一个自己的日 ...
- python 日志打印之logging使用介绍
python 日志打印之logging使用介绍 by:授客QQ:1033553122 测试环境: Python版本:Python 2.7 简单的将日志打印到屏幕 import logging lo ...
- python 日志的配置,python对日志封装成类,日志的调用
# python 日志的配置,python对日志封装成类,日志的调用 import logging # 使用logging模块: class CLog: # --------------------- ...
- python日志模块logging学习
介绍 Python本身带有logging模块,其默认支持直接输出到控制台(屏幕),或者通过配置输出到文件中.同时支持TCP.HTTP.GET/POST.SMTP.Socket等协议,将日志信息发送到网 ...
- Python 日志输出中添加上下文信息
Python日志输出中添加上下文信息 除了传递给日志记录函数的参数(如msg)外,有时候我们还想在日志输出中包含一些额外的上下文信息.比如,在一个网络应用中,可能希望在日志中记录客户端的特定信息,如: ...
- python日志模块笔记
前言 在应用中记录日志是程序开发的重要一环,也是调试的重要工具.但却很容易让人忽略.之前用flask写的一个服务就因为没有处理好日志的问题导致线上的错误难以察觉,修复错误的定位也很困难.最近恰好有时间 ...
随机推荐
- 题解 Smooth
传送门 咕了蚯蚓这题+前一天被蚊子折腾了半宿没睡=全场几乎就我这题分最低-- 发现这里光滑数是不断乘出来的--记得这是一个很经典的套路,然而当时我咕了 求一个每个值都是 \(\{p_i\}\) 中至少 ...
- springboot&&springcloud知识点
spring cloud 常见面试题: A.https://blog.csdn.net/panhaigang123/article/details/79587612 B.https://blog.cs ...
- Spring详解(九)------事务管理
1.事务介绍 事务(Transaction),一般是指要做的或所做的事情.在计算机术语中是指访问并可能更新数据库中各种数据项的一个程序执行单元(unit). 这里我们以取钱的例子来讲解:比如你去ATM ...
- xmake v2.5.7 发布,包依赖锁定和 Vala/Metal 语言编译支持
xmake 是一个基于 Lua 的轻量级跨平台构建工具,使用 xmake.lua 维护项目构建,相比 makefile/CMakeLists.txt,配置语法更加简洁直观,对新手非常友好,短时间内就能 ...
- Win7/Win10+VS2017+OpenCV3.4.2安装、测试
安装VS2017 在微软官网https://www.microsoft.com,下载Visual Studio 2017安装包 用管理员权限运行vs2017 enterprise安装包,安装过程会持续 ...
- Asp.NetCore ResposeCache 缓存的使用
先小结一下: 缓存策略: [ResponseCache(CacheProfileName ="default30")] 直接使用缓存,30秒过期: [ResponseCache(D ...
- php 字符串分割输出
分割字符串 //利用 explode 函数分割字符串到数组 复制代码代码如下:<?php $source = "hello1,hello2,hello3,hello4,hello5&q ...
- Centos8.3安装broadcom(博通)BCM43142无线网卡驱动,Centos8没有wifi选项(No wifi adapter found centos)解决办法
参考:杆菌大祭司> https://www.jianshu.com/p/3cb41b7b8fec 第一步:查看网卡型号,确认无线网卡型号为BCMXXX lspci | grep Network ...
- 前端搭建Linux云服务器,Nginx配置详解及部署自己项目到服务器上
目录 搭建Linux云服务器 购买与基本配置 链接linux服务器 目录结构 基本命令 软件安装 Linux 系统启动 启动过程 运行级别 Nginx详解 1.安装 方式一:yum安装 方式二:自定义 ...
- vue的常见理论问题
1.什么是 mvvm? mvvm 和 mvc 区别? MVVM 是 Model-View-ViewModel 的缩写.mvvm 是一种设计思想.Model 层代表数据模型,View 代表 UI 组件. ...