简体   繁体   English

Python TimedRotatingFileHandler - 缺少日志

[英]Python TimedRotatingFileHandler - logs are missing

I am running my python application in apache environment and using timedRotatingFileHandler to log. 我在apache环境中运行我的python应用程序并使用timedRotatingFileHandler进行记录。 I have setup logger in a way that It is supposed to rotate midnight everyday. 我设置记录器的方式应该是每天午夜轮换。 My all processes writes into the same logger file. 我的所有进程都写入同一个记录器文件。 Somehow logger is missing to log info at times. 某种程度上记录器有时会记录日志信息。 And sometimes I see logger writing into two files (old file and rotated file) at the same time. 有时我会看到记录器同时写入两个文件(旧文件和旋转文件)。

I couldn't able to understand why is this happening? 我无法理解为什么会这样? Doesn't TimedrotatingFileHandler work in multiprocess enivironment? TimedrotatingFileHandler不能在多进程环境中工作吗? If not why is that so? 如果不是为什么会这样?

Please help me to understand.. 请帮我理解..

You can't log (and rotate) to the same file from multiple processes naively because OS wouldn't know how to serialize the write and rotate instructions from 2 different processes. 您不能天真地从多个进程记录(和旋转)到同一文件,因为操作系统不知道如何序列化来自2个不同进程的写入和旋转指令。 What you are experiencing is known as a race condition as 2 processes are competing to write to the same file and close it and open with a new file handle at the same time at rotation time. 您遇到的情况称为竞争条件,因为2个进程正在竞争写入同一文件并关闭它并在旋转时同时使用新文件句柄打开。 Only 1 process will win a new file handle when you rotate, so that may explain the missing log event. 旋转时,只有1个进程将赢得新的文件句柄,这样可以解释丢失的日志事件。

Here's a recipe from Python's documentation with hints about how to log to the same place. 这是Python文档中的一个配方,提供了有关如何登录到同一位置的提示。

http://docs.python.org/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes http://docs.python.org/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes

Essentially you will want to have a separate process listening to logging events coming from multiple places and then that process will log the events to a single file. 基本上,您需要一个单独的进程监听来自多个位置的日志记录事件,然后该进程将事件记录到单个文件中。 You can configure rotation in that listener process too. 您也可以在该侦听器进程中配置旋转。

If you are not sure how to write this, you can try using a package such as Sentry or Facebook's Scribe . 如果你不确定如何写这个,你可以尝试使用像Sentry或Facebook的Scribe这样的软件包。 I recommend Sentry because Scribe is not trivial to setup. 我推荐Sentry,因为Scribe并不容易设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM