python WatchedFileHandler 旋转后仍在写入旧文件

标签 python logging rotation

我一直在使用 WatchedFileHandler作为我的 python 日志记录文件处理程序,以便我可以使用 logrotate(在 ubuntu 14.04 上)轮换我的日志,你知道这就是文档所说的。我的 logrotate 配置文件看起来像

/path_to_logs/*.log {
        daily
        rotate 365
        size 10M
        compress
        delaycompress
        missingok
        notifempty
        su root root
}

一切似乎都运行良好。我正在使用 logstash 将我的日志发送到我的 elasticsearch 集群,一切都很好。我为我的调试日志添加了第二个日志文件,该文件会轮换但不会被 logstash 监视。我注意到,当该文件被轮换时,python 只会继续写入 /path_to_debug_logs/*.log.1 并且永远不会开始写入新文件。如果我手动尾随 /path_to_debug_logs/*.log.1,它会立即切换并开始写入 /path_to_debug_logs/*.log

这对我来说真的很奇怪。

我相信正在发生的事情是 logstash 总是拖尾我的非调试日志,这在某种程度上触发了在 logrotate 被调用后切换到新文件。如果 logrotate 在没有切换的情况下被调用两次,log.1 文件将被移动并压缩到 log.2.gz,python 无法再登录到该文件并且日志将丢失。

很明显,对此有很多 hacky 解决方案(例如 cronjob 时不时跟踪我的所有日​​志),但我觉得我一定做错了什么。

出于多种原因,我使用 WatchedFileHandlerlogrotate 而不是 RotatingFileHandler,但主要是因为它可以很好地压缩我的日志旋转后的我。

更新:

我尝试了在我的日志轮换配置脚本末尾添加手动尾部的可怕技巧。

sharedscripts
postrotate
    /usr/bin/tail -n 1 path_to_logs/*.log.1
endscript

果然这在大多数情况下都有效,但有时会无缘无故地随机失败,所以这不是解决方案。我还尝试了一些不那么棘手的解决方案,我修改了 WatchFileHandler 检查文件是否已更改的方式,但没有成功。

我相当确定我的问题的根源是日志存储在网络驱动器上,这在某种程度上混淆了文件系统。

我正在使用 RotatingFileHandler 将我的旋转移动到 python,但如果有人知道处理这个问题的正确方法,我很想知道。

最佳答案

使用 logrotate 的 copytruncate 选项。来自 docs

copytruncate

Truncate the original log file in place after creating a copy, instead of moving the old log file and optionally creating a new one, It can be used when some program can not be told to close its logfile and thus might continue writing (appending) to the previous log file forever. Note that there is a very small time slice between copying the file and truncating it, so some logging data might be lost. When this option is used, the create option will have no effect, as the old log file stays in place.

关于python WatchedFileHandler 旋转后仍在写入旧文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35298708/

相关文章:

python - 如何获得整数的加法对象?

python - 使用 Python 标准库的跨平台声音

python - 跟踪前端电影进程的进度

java - Camel 主体是用请求而不是响应设置的

ios - 如何在 iOS 8 中使用旋转

python - 我可以在仅使用非空值的行之间使用余弦相似度吗?

logging - kube-controller-manager 未出现在 Google Kubernetes Engine 上

python - captureWarnings 设置为 True 不捕获警告

java - 设置移动和旋转物体上的推力位置

matrix - 在非标准二维平面中旋转矩阵