Python logging with python-daemon

223 Views Asked by At

I have a script that I try do daemonize, using python-daemon

This is the relevant method:

def run(self) -> None:
    """main loop"""
    context = daemon.DaemonContext()
    context.signal_map = {signal.SIGTERM: DaemonLoop._stop}
    log_handlers = logging.getLogger("").handlers
    context.files_preserve = [handler.stream.fileno() for handler in log_handlers]

    LOG.info("before daemonization")
    context.open()
    LOG.info("after daemonization")
    with context:
        while True:
            # self._main()
            LOG.info("test")
            time.sleep(1)

"before daemonization" is logged (file + terminal), but "after daemonization" is not.

I have 2 log handlers, terminal + files:

enter image description here

I searched other answers to similar question (files_preserve and logging configuration after context.open()), but none of them is working in my case. What should I do?

1

There are 1 best solutions below

0
dmitri On

You are adding fileno(), but you need to add a stream object or, maybe, a socket

context.files_preserve = []
for h in logger.handlers:
    o = getattr(h, 'stream', None)
    if not o:
        o = getattr(h, 'socket', None)
    if o:   
        context.files_preserve.append(o)

File logger uses stream, syslog logger uses socket.

As a side note: I couldn't make Google Cloud Logging work in a daemon. The call to fork destroys threads and makes GCP logger defunct. Instead, I am using systemd to run my Python script as a service.