基础
简单控制台打印
import logging
logging.basicConfig()
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
简单写入文件
import logging
logging.basicConfig(filename="test.log", filemode="w", format="%(asctime)s %(name)s:%(levelname)s:%(message)s", datefmt="%d-%M-%Y %H:%M:%S", level=logging.DEBUG)
logging.debug('This is a debug message')
文件生成内容如下:
13-10-18 21:10:32 root:DEBUG:This is a debug message
进阶
logging库和rich库组合
import logging
try:
from rich.logging import RichHandler
handler = RichHandler(show_path=False, show_time=False)
logging.basicConfig(
level=logging.INFO, handlers=[handler], format="%(message)s", force=True
)
except ImportError:
logging.basicConfig(level=logging.INFO, format="%(levelname)s\t %(message)s", force=True)
同时输出屏幕和文件
from datetime import datetime
from pathlib import Path
import logging
from rich.logging import RichHandler
Path("log").mkdir(exist_ok=True)
rich_handler = RichHandler(show_path=False, show_time=False, level=logging.INFO)
file_handler = logging.FileHandler(
"log/{}.log".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S")), "w"
)
file_handler.setLevel(logging.ERROR)
logging.basicConfig(
level=logging.INFO,
handlers=[rich_handler, file_handler],
format="%(message)s",
force=True,
)
关闭第三方库的日志
import logging
httpx_logger=logging.getLogger("httpx")
httpx_logger.setLevel(logging.CRITICAL) #通过调高警报等级来取消
httpx_logger.propagate = False #也可以直接取消
附录:format参数的可选变量
注意不要漏了末尾的s
字段名称 | 使用格式 | 描述 |
---|---|---|
asctime | %(asctime)s | 将日志的时间构造成可读的形式,默认情况下是‘2016-02-08 12:00:00,123’精确到毫秒 |
name | %(name)s | 所使用的日志器名称,默认是’root’,因为默认使用的是 rootLogger |
filename | %(filename)s | 调用日志输出函数的模块的文件名;pathname的文件名部分,包含文件后缀 |
funcName | %(funcName)s | 由哪个function发出的log, 调用日志输出函数的函数名 |
levelname | %(levelname)s | 日志的最终等级(被filter修改后的) |
message | %(message)s | 日志信息, 日志记录的文本内容 |
lineno | %(lineno)d | 当前日志的行号, 调用日志输出函数的语句所在的代码行 |
levelno | %(levelno)s | 该日志记录的数字形式的日志级别(10, 20, 30, 40, 50) |
pathname | %(pathname)s | 完整路径 ,调用日志输出函数的模块的完整路径名,可能没有 |
process | %(process)s | 当前进程, 进程ID。可能没有 |
processName | %(processName)s | 进程名称,Python 3.1新增 |
thread | %(thread)s | 当前线程, 线程ID。可能没有 |
threadName | %(thread)s | 线程名称 |
module | %(module)s | 调用日志输出函数的模块名, filename的名称部分,不包含后缀即不包含文件后缀的文件名 |
created | %(created)f | 当前时间,用UNIX标准的表示时间的浮点数表示;日志事件发生的时间–时间戳,就是当时调用time.time()函数返回的值 |
relativeCreated | %(relativeCreated)d | 输出日志信息时的,自Logger创建以 来的毫秒数;日志事件发生的时间相对于logging模块加载时间的相对毫秒数 |
msecs | %(msecs)d | 日志事件发生事件的毫秒部分。logging.basicConfig()中用了参数datefmt,将会去掉asctime中产生的毫秒部分,可以用这个加上 |