发布于2026-07-03 阅读(0)
扫一扫,手机访问
在Linux环境下配置Python日志,很多人上来就抄一段代码,但真正理解配置逻辑的人并不多。今天就从一个最常用的场景说起——怎么让日志既保留调试细节,又不把生产环境撑爆。

先看最直观的方式,直接用Python内置的logging模块。整个过程分三步走:
import logging搞定。basicConfig一次性定义日志级别、格式、输出文件等参数。logging.debug()、logging.info()这些方法向日志里写内容。举个例子,下面的配置会把日志写到当前目录下的app.log文件里,日志级别设为DEBUG,意味着所有级别(DEBUG、INFO、WARNING、ERROR、CRITICAL)都会被记录。
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='app.log',
filemode='a'
)
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
filemode='a'表示追加写入,如果你希望每次启动都重新生成日志文件,改成'w'就行。这里特别提醒一下:生产环境中level一般不会设成DEBUG,否则日志量会非常可观,通常用INFO或WARNING起步。
上面的方式适合快速验证,但项目上了规模,硬编码配置就显得笨拙了。这时候推荐用配置文件来管理日志设置。先创建一个logging.conf文件,内容如下:
[loggers]
keys=root
[handlers]
keys=fileHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=fileHandler
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=('app.log', 'a')
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S
然后在Python代码里通过logging.config.fileConfig()加载这个配置文件:
import logging
import logging.config
logging.config.fileConfig('logging.conf')
logger = logging.getLogger(__name__)
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')
这样做的最大好处是:调整日志级别、输出位置、格式都不需要改代码,改一下配置文件再重载即可。对于需要频繁切换调试模式的项目,这个思路值得养成习惯。
当然,配置文件也可以写成YAML或JSON格式,但.conf风格是Python社区最原生的选择,零依赖,适用面最广。如果将来需要更复杂的日志路由(比如不同模块写不同文件、按天滚动等),可以在配置文件里追加handlers和formatters的定义,这部分扩展起来很灵活。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8