Python 日志模块使用

本文最后更新于 2024年4月26日 凌晨

将日志导出到文件【方法一】

1
2
3
4
5
6
7
8
9
10
11
12
import logging

# https://docs.python.org/zh-cn/3/library/logging.html#logging.basicConfig
logging.basicConfig(
filename='path/to/example.log',
format='%(asctime)s-%(name)s-%(levelname)s-%(message)s',
level=logging.DEBUG
)

logging.debug('Debug message')
logging.info('Info message')
logging.warning('Warning message')

*实测,Colab 中新建的日志文件只有当 running time 结束后才会出现。

将日志导出到文件【方法二】

1
2
3
4
5
6
7
8
9
10
11
12
13
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')

file_handler = logging.FileHandler('path/to/example.log')
file_handler.setFormatter(formatter)

logger.addHandler(file_handler)

logger.info('This is an Info message')

*实测,Colab 中此方法无法写入到文件,会输出到控制台,暂未找到原因。

参考/扩展


Python 日志模块使用
https://blog.cc01cc.cn/2023/04/30/python-logging/
作者
零一/cc01cc(zeo)
发布于
2023年4月30日
更新于
2024年4月26日
许可协议