python 的 日志模块怎么编写
时间: 2024-02-16 10:03:48 浏览: 24
Python内置的日志模块可以用来记录应用程序的运行情况、调试信息、错误信息等。下面是使用Python日志模块的基本步骤:
1. 导入日志模块
```
import logging
```
2. 配置日志
可以通过`basicConfig()`方法进行简单的日志配置,例如设置日志级别、输出格式等。也可以通过`Logger`类来进行更详细的配置。
```
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
```
3. 创建Logger对象
```
logger = logging.getLogger(__name__)
```
4. 记录日志
可以使用`debug()`、`info()`、`warning()`、`error()`和`critical()`等方法来记录不同级别的日志。
```
logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')
```
此外,还可以设置日志处理器(Handler)来将日志输出到不同的地方,例如文件、控制台等。
完整的示例代码:
```
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')
```