from loguru import loggerlogger.debug('This is debug information')logger.info('This is info information')logger.warning('This is warn information')logger.error('This is error information')
from loguru import loggerlogger.add("E:/Old Boy/day_projects/日志模块/log_2023-8-7.log",rotation="500MB", encoding="utf-8", enqueue=True, retention="10 days")logger.info('This is info information')
终端显示结果
2023-08-07 22:47:11.611 | INFO | __main__::19 - This is info information
如上,loguru直接通过 add() 方法,完成了日志文件的配置。
【五】日志内容的字符串格式化
loguru 在输出 日志的时候,还提供了非常灵活的字符串格式化输出日志的功能,如下:
import platformfrom loguru import loggerrounded_value = round(0.345, 2)trace= logger.add('2023-8-7.log')logger.info('If you are using Python {version}, prefer {feature} of course!', version=platform.python_version(), feature='f-strings')
执行上述代码,输出结果为
2023-08-07 22:46:03.812 | INFO | __main__::21 - If you are using Python 3.9.13, prefer f-strings of course!
add 方法 添加 sink 之后我们也可以对其进行删除, 删除的时候根据刚刚 add 方法返回的 id 进行删除即可,还原到标准输出。如下:
from loguru import loggertrace = logger.add('2021-8-7.log')logger.error('This is error information')logger.remove(trace)logger.warning('This is warn information')
终端显示结果
2023-08-07 22:50:37.834 | ERROR| __main__::17 - This is error information2023-08-07 22:50:37.834 | WARNING| __main__::20 - This is warn information
日志2023-8-7.log内容如下
2023-08-07 22:50:37.834 | ERROR| __main__::17 - This is error information
from loguru import logger# 清除之前的设置logger.remove(handler_id=None)trace = logger.add('2023-8-7.log')logger.error('This is error information')logger.warning('This is warn information')
2023-08-07 22:54:11 WARNING From 01 日志模块测试.format_log : This is warn information
【4】enqueue 异步写入
logger.add("2023-8-7.log", enqueue=True)
使用enqueue,可保证线程安全,多线程安全。
【5】其它的格式化模板属性 如下:
Key
Description
elapsed
从程序开始经过的时间差
exception
格式化异常(如果有),否则为’ None ‘
extra
用户绑定的属性字典(参见bind())
file
进行日志记录调用的文件
function
进行日志记录调用的函数
level
用于记录消息的严重程度
line
源代码中的行号
message
记录的消息(尚未格式化)
module
进行日志记录调用的模块
name
进行日志记录调用的__name__
process
进行日志记录调用的进程名
thread
进行日志记录调用的线程名
time
发出日志调用时的可感知的本地时间
(1)通过 extra bind() 添加额外属性来为结构化日志提供更多属性信息
如下:
from loguru import loggerdef format_log():"""Returns:"""trace = logger.add('2023-8-7.log', format="{time:YYYY-MM-DD HH:mm:ss} {extra[ip]}{extra[username]} {level} From {module}.{function} : {message}")extra_logger = logger.bind(ip="192.168.0.1", username="张三")extra_logger.info('This is info information')extra_logger.bind(username="李四").error("This is error information")extra_logger.warning('This is warn information')if __name__ == '__main__':format_log()
终端显示
2023-08-07 22:56:16.435 | INFO | __main__:format_log:27 - This is info information2023-08-07 22:56:16.435 | ERROR| __main__:format_log:28 - This is error information2023-08-07 22:56:16.436 | WARNING| __main__:format_log:30 - This is warn information
如下,我们可以看到在 2023-8-7.log 日志文件中,看到日志按上述模板记录,如下:
2023-08-07 22:56:16 192.168.0.1张三 INFO From 01 日志模块测试.format_log : This is info information2023-08-07 22:56:16 192.168.0.1李四 ERROR From 01 日志模块测试.format_log : This is error information2023-08-07 22:56:16 192.168.0.1张三 WARNING From 01 日志模块测试.format_log : This is warn information
(2)level 配置日志最低日志级别
from loguru import loggertrace = logger.add('2023-8-7.log', level='ERROR')
from loguru import loggerimport platformrounded_value = round(0.345, 2)trace= logger.add('2023-8-7.log', serialize=True)logger.info('If you are using Python {version}, prefer {feature} of course!', version=platform.python_version(), feature = 'f-strings')
终端显示
2023-08-07 23:01:14.356 | INFO | __main__::21 - If you are using Python 3.9.13, prefer f-strings of course!
在2023-8-7.log日志文件,我们可以看到每条日志信息都被序列化后存在日志文件中,如下:
{"text": "2023-08-07 23:01:14.356 | INFO | __main__::21 - If you are using Python 3.9.13, prefer f-strings of course!\n","record": {"elapsed": {"repr": "0:00:00.018001", "seconds": 0.018001},"exception": null,"extra": {"version": "3.9.13", "feature": "f-strings"},"file": {"name": "01 日志模块测试.py","path": "E:\\day_projects\\日志模块\\01 日志模块测试.py"},"function": "","level": {"icon": "\u2139\ufe0f","name": "INFO","no": 20},"line": 9,"message": "If you are using Python 3.9.13, prefer f-strings of course!","module": "01 日志模块测试","name": "__main__","process": {"id": 21636,"name": "MainProcess"},"thread": {"id": 28612, "name": "MainThread"},"time": {"repr": "2023-08-07 23:01:14.356111+08:00","timestamp": 1691420474.356111}}}
2023-08-07 23:08:12.010 | ERROR| __main__::30 - An error has been caught in function '', process 'MainProcess' (17440), thread 'MainThread' (26612):Traceback (most recent call last):> File "E:\Old Boy\day_projects\日志模块\01 日志模块测试.py", line 30, in index_error([1, 2, 3])└ File "E:\Old Boy\day_projects\日志模块\01 日志模块测试.py", line 22, in index_errorindex_value = custom_list[index]│ └ 2└ [2, 3]IndexError: list index out of range
同时,附上对类中的类方法和静态方法的代码实例,以供参考
from loguru import loggertrace = logger.add('2023-8-7.log')class Demo:@logger.catchdef index_error(self, custom_list: list):for index in range(len(custom_list)):index_value = custom_list[index]if custom_list[index] < 2:custom_list.remove(index_value)@staticmethod@logger.catchdef index_error_static(custom_list: list):for index in range(len(custom_list)):index_value = custom_list[index]if custom_list[index] < 2:custom_list.remove(index_value)if __name__ == '__main__':# Demo().index_error([1, 2, 3])Demo.index_error_static([1, 2, 3])
(8)通过 logger.exception 方法也可以实现异常的捕获与记录:
from loguru import loggertrace = logger.add('2023-8-7.log')def index_error(custom_list: list):for index in range(len(custom_list)):try:index_value = custom_list[index]except IndexError as err:logger.exception(err)breakif custom_list[index] < 2:custom_list.remove(index_value)if __name__ == '__main__':index_error([1, 2, 3])
终端打印
2023-08-07 23:11:16.587 | ERROR| __main__:index_error:24 - list index out of rangeTraceback (most recent call last):File "E:\Old Boy\day_projects\日志模块\01 日志模块测试.py", line 32, in index_error([1, 2, 3])└ > File "E:\Old Boy\day_projects\日志模块\01 日志模块测试.py", line 22, in index_errorindex_value = custom_list[index]│ └ 2└ [2, 3]IndexError: list index out of range