daemon.DaemonContext and logging

Ben Finney ben+python at benfinney.id.au
Sat Apr 10 23:52:41 EDT 2010

Sean DiZazzo <half.italian at gmail.com> writes:

> I'm finally getting around to trying out the python-daemon module and
> have hit a wall.  I'm trying to set up logging inside of the "with
> daemon.DaemonContext" block.  But when I try to use a logger inside
> the block it throws an error:

Specifically, it's throwing an error because a logger set up *outside*
the context is no longer open *inside* the context.

> handler = logging.FileHandler("log.file")
> logger.addHandler(handler)
> pid = daemon.pidlockfile.TimeoutPIDLockFile("/var/run/daemontest.pid",
> 10)
> with daemon.DaemonContext(pidfile=pid, gid=0, uid=0,
> stdout=sys.stdout, stderr=sys.stderr):
>     logger.info("POO")

Here, the daemon.DaemonContext has not been told to preserve the file
descriptor that was opened by ‘handler’; so that file descriptor gets
closed along with all the others when the DaemonContext opens.

Also, there's no point binding the ‘stdout’ and ‘stderr’ options to the
system streams as you've done: as the documentation specifies, becoming
a daemon process involves detaching from the controlling terminal, so
those streams will no longer be connected to anything.

If you want specific file descriptors to remain open, you need to tell
the DaemonContext which ones they are via the ‘files_preserve’ option:

    #! /usr/bin/python
    # -*- coding: utf-8; -*-

    from __future__ import with_statement

    import logging
    import daemon
    import daemon.pidlockfile
    import sys

    logger = logging.getLogger("DaemonLog")
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    handler = logging.FileHandler("log.file")

    pid = daemon.pidlockfile.TimeoutPIDLockFile(
        "/tmp/dizazzo-daemontest.pid", 10)

    daemon_context = daemon.DaemonContext(

    with daemon_context:

Thanks for this question; it's now in the FAQ document for the next

> Any advice? Also, I left in the call to TimeoutPIDLockfile() as well,
> because the library's documentation is pretty sparse, and I want to
> know if I'm using it properly.

Improvements to the documentation would be welcome, certainly.

 \         “We now have access to so much information that we can find |
  `\  support for any prejudice or opinion.” —David Suzuki, 2008-06-27 |
_o__)                                                                  |
Ben Finney

More information about the Python-list mailing list