简体   繁体   中英

Python-daemon: keep logging

I have a script that logs a bit of data to disk:

logging.basicConfig(filename='davis-debug.log',level=logging.DEBUG) logging.basicConfig(filename='davis-error.log',level=logging.ERROR) logging.basicConfig(filename='davis-error.log',level=logging.WARNING) logging.basicConfig(filename='davis-error.log',level=logging.CRITICAL)

When i use python-daemon like this, the logging stops.

try:
  with daemon.DaemonContext():
  station = VantageProStation()
  station.run()

except KeyboardInterrupt:
  logging.critical('Stopping user aborted with CTRL+C')
pass

I have tried file_preserve, but logging.basicConfig does not return a stream.
Also i cannot pass several streams using files_preserve..?
I afcourse want my logging to continue, i tried to put the log definion inside my class init that did not help either.

What about configuring your logger inside your daemon ? This works for me :

#!/usr/bin/env python

import daemon
import logging
import logging.handlers
from time import sleep
from datetime import datetime

def time_logging_daemon():
    logger = logging.getLogger('time_logging_daemon')
    logger.addHandler(logging.handlers.SysLogHandler(address='/dev/log'))
    logger.setLevel(logging.INFO)
    while True:
        logger.info(datetime.now())
        sleep(1)

with daemon.DaemonContext():
    time_logging_daemon()

The daemon context closes all file handlers to be "well behaved daemon" except the ones specified in the files_preserve . You were in the right direction.

There is a way to get the file handler from logging but I suggest that you create the file logger explicitly.

#!/usr/bin/env python

import daemon
import logging
import logging.handlers
from time import sleep
from datetime import datetime

logging.basicConfig()

file_logger = logging.FileHandler("/tmp/aaa.log", "w")

logger = logging.getLogger()
logger.addHandler(file_logger)
logger.setLevel(logging.INFO)

with daemon.DaemonContext(files_preserve=[file_logger.stream.fileno()]):
    while True:
        logger.info(datetime.now())
        sleep(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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