Every recipe that I've found for creating a daemon process in Python involves forking twice (for Unix) and then closing all open file descriptors. (See http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ for an example).
This is all simple enough but I seem to have an issue. On the production machine that I am setting up, my daemon is aborting - silently since all open file descriptors were closed. I am having a tricky time debugging the issue currently and am wondering what the proper way to catch and log these errors are.
What is the right way to setup logging such that it continues to work after daemonizing? Do I just call logging.basicConfig()
a second time after daemonizing? What's the right way to capture stdout
and stderr
? I am fuzzy on the details of why all the files are closed. Ideally, my main code could just call daemon_start(pid_file)
and logging would continue to work.
We just had a similar issue, and due to some things beyond my control, the daemon stuff was separate from the stuff creating the logger. However, logger has a .handlers and .parent attributes that make it possible with something like:
You can simplify the code for this if you set up your logging handler objects separately from your root logger object, and then add the handler objects as an independent step rather than doing it all at one time. The following should work for you.
I use the
python-daemon
library for my daemonization behavior.Interface described here:
Implementation here:
It allows specifying a
files_preserve
argument, to indicate any file descriptors that should not be closed when daemonizing.If you need logging via the same
Handler
instances before and after daemonizing, you can:basicConfig
ordictConfig
or whatever.Handler
s depend on. Unfortunately this is dependent on theHandler
subclass. If your first-installedHandler
is aStreamHandler
, it's the value oflogging.root.handlers[0].stream.fileno()
; if your second-installedHandler
is aSyslogHandler
, you want the value oflogging.root.handlers[1].socket.fileno()
; etc. This is messy :-(DaemonContext
withfiles_preserve
equal to a list of the file descriptors you determined in step 3.An alternative might be, as @Exelian suggested, to actually use different
Handler
instances before and after the daemonziation. Immediately after daemonizing, destroy the existing handlers (bydel
ing them fromlogger.root.handlers
?) and create identical new ones; you can't just re-callbasicConfig
because of the issue that @dave-mankoff pointed out.