filter
from datetime import datetime
import sys
from loguru import logger
logger.remove()
def file1_filter(record):
print('file_filter record["extra"]:', record["extra"])
return record["extra"].get("file1", False)
def console_filter(record):
print('console_filter record["extra"]:', record["extra"])
return not record["extra"]
# 添加 3 个 handler ,每次调用 logger.info 都会依次调用所有 handler
logger.add(sys.stderr, filter=console_filter, format='<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{file}</cyan>:<cyan>{line}</cyan> :<cyan>{function}</cyan> - {message}')
logger.add('file1.txt', filter=file1_filter, format="{message}",retention="3 days")
logger.add('file2.txt', filter=file1_filter, format="{message}",retention="3 days")
# 创建 2 个新的 logger 绑定到主 logger 中,它们共享同一组 handler ,唯一的区别是 record["extra"] 不同
file1 = logger.bind(file1=True)
file2 = logger.bind(file2=True)
print("---- logger.info('logger') -----")
logger.info('logger')
print("---- file1.info('file1') -----")
file1.info('file1')
print("---- file2.info('file2') -----")
file2.info('file2')
输出及解释:
# logger 用 logger.bind 的方式赋值 record["extra"] ,所以输出均为空
---- logger.info('logger') -----
# 调用 handler sys.stderr ,判断 console_filter 返回值为 True ,因此输出内容
console_filter record["extra"]: {}
2023-11-12 01:41:05 | INFO | log_test.py:26 :<module> - logger
# 调用 handler 'file1.txt' ,判断 file1_filter 返回值为 False ,因此内容不会被输出到 file1.txt
file_filter record["extra"]: {}
file_filter record["extra"]: {}
# file1 用 file1 = logger.bind(file1=True) 的方式赋值 record["extra"]['file1']=True ,所以可以看到这个 file1 logger 输出了 {'file1': True}
---- file1.info('file1') -----
# 调用 handler sys.stderr ,判断 console_filter 返回值为 False ,因此内容不会输出到终端
console_filter record["extra"]: {'file1': True}
# 调用 handler 'file1.txt' ,判断 file1_filter 返回值 True ,将内容输出到 file1.txt
file_filter record["extra"]: {'file1': True}
# 调用 handler 'file2.txt' ,判断 file1_filter 返回值 False ,内容不会输出到 file2.txt
file_filter record["extra"]: {'file1': True}
---- file2.info('file2') -----
console_filter record["extra"]: {'file2': True}
file_filter record["extra"]: {'file2': True}
file_filter record["extra"]: {'file2': True}
# file1.txt 内容
file1
# file2.txt 没有内容