windows下 python将运行程序的日志按天写入
时间: 2023-12-21 10:05:05 浏览: 26
可以使用 Python 标准库中的 logging 模块来实现将运行程序的日志按天写入的功能。具体步骤如下:
1. 导入 logging 模块
```python
import logging
```
2. 配置 logging
```python
# 创建 Logger 对象
logger = logging.getLogger()
# 设置日志级别为 DEBUG,即输出所有级别的日志
logger.setLevel(logging.DEBUG)
# 创建一个按天分割日志的处理器
log_file = f"log/{datetime.datetime.now().strftime('%Y-%m-%d')}.log"
handler = logging.handlers.TimedRotatingFileHandler(
log_file, when='midnight', interval=1, backupCount=7)
# 设置输出格式
formatter = logging.Formatter(
'%(asctime)s %(levelname)-8s %(message)s', '%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
# 将处理器添加到 Logger 对象中
logger.addHandler(handler)
```
- `logger.setLevel(logging.DEBUG)`:设置日志级别为 DEBUG,这样所有级别的日志都会被记录。
- `log_file`:设置日志文件的路径和文件名,使用了当前日期来动态生成文件名。
- `logging.handlers.TimedRotatingFileHandler`:创建按天分割的日志处理器。
- `handler.setFormatter(formatter)`:设置日志的输出格式,此处使用了时间、级别和消息三个字段。
3. 记录日志
```python
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')
```
- `logger.debug`:记录 debug 级别的日志。
- `logger.info`:记录 info 级别的日志。
- `logger.warning`:记录 warning 级别的日志。
- `logger.error`:记录 error 级别的日志。
- `logger.critical`:记录 critical 级别的日志。
这样就可以实现将运行程序的日志按天写入的功能了。注意,需要先创建一个名为“log”的文件夹来存储日志文件。