www.colben.cn/content/post/python-logging.md
2021-11-14 15:52:46 +08:00

78 lines
3.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: "Python 的 logging 模块"
date: 2019-10-30T18:03:55+08:00
lastmod: 2019-10-30T18:03:55+08:00
tags: ["python", "logging"]
categories: ["python"]
---
## 单输出日志到屏幕
- 示例
```python
import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
```
- 输出
```python
WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message
```
- 默认情况下python的logging模块将日志打印到了标准输出中且只显示了大于等于WARNING级别的日志。
- 默认的日志级别设置为WARNING日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET
- 默认的日志格式为日志级别:Logger名称:用户输出消息。
## 配置日志
- 示例
```python
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='/tmp/test.log',
filemode='w')
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
```
- 输出
```python
cat /tmp/test.log
Mon, 05 May 2014 16:29:53 test_logging.py[line:9] DEBUG debug message
Mon, 05 May 2014 16:29:53 test_logging.py[line:10] INFO info message
Mon, 05 May 2014 16:29:53 test_logging.py[line:11] WARNING warning message
Mon, 05 May 2014 16:29:53 test_logging.py[line:12] ERROR error message
Mon, 05 May 2014 16:29:53 test_logging.py[line:13] CRITICAL critical message
```
- logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为参数解释
- filename用指定的文件名创建FiledHandler后边会具体讲解handler的概念这样日志会被存储在指定的文件中。
- filemode文件打开方式在指定了filename时使用这个参数默认值为“a”还可指定为“w”。
- format指定handler使用的日志显示格式。
- datefmt指定日期时间格式。
- level设置rootlogger后边会讲解具体概念的日志级别
- stream用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件默认为sys.stderr。若同时列出了filename和stream两个参数则stream参数会被忽略。
- format参数中可能用到的格式化串
- %(name)s Logger的名字
- %(levelno)s 数字形式的日志级别
- %(levelname)s 文本形式的日志级别
- %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
- %(filename)s 调用日志输出函数的模块的文件名
- %(module)s 调用日志输出函数的模块名
- %(funcName)s 调用日志输出函数的函数名
- %(lineno)d 调用日志输出函数的语句所在的代码行
- %(created)f 当前时间用UNIX标准的表示时间的浮 点数表示
- %(relativeCreated)d 输出日志信息时的自Logger创建以 来的毫秒数
- %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
- %(thread)d 线程ID。可能没有
- %(threadName)s 线程名。可能没有
- %(process)d 进程ID。可能没有
- %(message)s用户输出的消息