Files
ailearning/docs/da/146.md
2020-10-19 21:08:55 +08:00

76 lines
1.3 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# logging 模块:记录日志
`logging` 模块可以用来记录日志:
In [1]:
```py
import logging
```
`logging` 的日志类型有以下几种:
* `logging.critical(msg)`
* `logging.error(msg)`
* `logging.warning(msg)`
* `logging.info(msg)`
* `logging.debug(msg)`
级别排序为:`CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET`
默认情况下,`logging` 的日志级别为 `WARNING`,只有不低于 `WARNING` 级别的日志才会显示在命令行。
In [2]:
```py
logging.critical('This is critical message')
logging.error('This is error message')
logging.warning('This is warning message')
# 不会显示
logging.info('This is info message')
logging.debug('This is debug message')
```
```py
CRITICAL:root:This is critical message
ERROR:root:This is error message
WARNING:root:This is warning message
```
可以这样修改默认的日志级别:
In [3]:
```py
logging.root.setLevel(level=logging.INFO)
logging.info('This is info message')
```
```py
INFO:root:This is info message
```
可以通过 `logging.basicConfig()` 函数来改变默认的日志显示方式:
In [4]:
```py
logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s')
logger = logging.getLogger("this program")
logger.critical('This is critical message')
```
```py
CRITICAL:this program:This is critical message
```