如何使用python日志模块防止日志文件截断?

2024-04-29 11:05:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用python日志模块将调试信息打印到一个包含如下语句的文件中:

logging.debug(something)

文件被截断了(我假设-被日志模块截断了),消息在我看到它们之前被删除了-怎么能阻止呢?

这是我的日志配置:

logging.basicConfig(
    level = logging.DEBUG,
    format = '%(asctime)s %(levelname)s %(message)s',
    filename = '/tmp/my-log.txt',
    filemode = 'w'
)

谢谢!


Tags: 模块文件debugformat消息messagelogging语句
1条回答
网友
1楼 · 发布于 2024-04-29 11:05:16

^{}

If you run the script repeatedly, the additional log messages are appended to the file. To create a new file each time, you can pass a filemode argument to basicConfig() with a value of 'w'. Rather than managing the file size yourself, though, it is simpler to use a RotatingFileHandler.

要防止覆盖文件,不应将filemode设置为'w',或set it to ^{}(这是默认设置)。

我相信你只是在重写文件。

相关问题 更多 >