阅读python日志文档
This commit is contained in:
49
python/py log.md
Normal file
49
python/py log.md
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
# python log
|
||||||
|
## Logging use
|
||||||
|
可以通过`logger = getLogger(__name__)`创建一个logger,之后可以通过logger来访问日志功能。
|
||||||
|
|
||||||
|
针对logger对象,可以调用`debug(), info(), warning(), error(), critical()`方法。
|
||||||
|
|
||||||
|
python中,日志级别及其适用性如下:
|
||||||
|
| 级别 | 实用性 |
|
||||||
|
| :-: | :-: |
|
||||||
|
| DEBUG | 详细信息,通常只在调试时用到 |
|
||||||
|
| INFO | 用于确认应用正在按照预期执行 |
|
||||||
|
| WARNING | 代表存在非预期事件发生,但是应用仍然按期望运行 |
|
||||||
|
| ERROR | 代表应用存在问题,部分功能可能无法正常访问 |
|
||||||
|
| CRITIAL | 严重错误,代表应用不能继续执行 |
|
||||||
|
|
||||||
|
logger默认的隔离级别是`WARNING`, 只有`WARNING`隔离级别或更高的隔离级别,日志才会被输出。该默认隔离级别也可以手动修改。
|
||||||
|
|
||||||
|
## 日志使用简单示例
|
||||||
|
```python
|
||||||
|
import logging
|
||||||
|
logging.warning('Watch out!') # will print a message to the console
|
||||||
|
logging.info('I told you so') # will not print anything
|
||||||
|
```
|
||||||
|
上述示例,其会输出
|
||||||
|
```
|
||||||
|
WARNING:root:Watch out!
|
||||||
|
```
|
||||||
|
> 默认输出的日志隔离级别为WARNING,info信息并不会被输出
|
||||||
|
|
||||||
|
当直接调用`logging`中的方法时,其并没有创建logger对象,方法调用是针对`root logger`对象的。
|
||||||
|
|
||||||
|
## loggging to file
|
||||||
|
将日志输出到文件的示例如下所示:
|
||||||
|
```python
|
||||||
|
import logging
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
|
||||||
|
logger.debug('This message should go to the log file')
|
||||||
|
logger.info('So should this')
|
||||||
|
logger.warning('And this, too')
|
||||||
|
logger.error('And non-ASCII stuff, too, like Øresund and Malmö')
|
||||||
|
```
|
||||||
|
其输出内容如下所示:
|
||||||
|
```
|
||||||
|
DEBUG:__main__:This message should go to the log file
|
||||||
|
INFO:__main__:So should this
|
||||||
|
WARNING:__main__:And this, too
|
||||||
|
ERROR:__main__:And non-ASCII stuff, too, like Øresund and Malmö
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user