My script logs to a file just fine until I try to fork it into the background at which point the file handle is closed, even if I use filesPreserve. How can I improve this in a lightweight fashion so that my logger runs in the background?
#!/usr/bin/env python
from socket import *
import sys, time, logging
import daemon
context = daemon.DaemonContext()
logger = logging.getLogger('audit')
hdlr = logging.FileHandler('/mnt/audit.log')
formatter = logging.Formatter('%(asctime)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.WARNING)
context.filesPreserve = [hdlr]
with context:
HOST = ''
PORT = 50007
ADDR = (HOST,PORT)
BUFSIZE = 4096 #reasonably sized buffer for data
serv = socket( AF_INET,SOCK_STREAM)
serv.bind((ADDR))
serv.listen(5) #5 is the maximum number of queued connections we'll allow
while True:
conn, addr = serv.accept()
sys.stdout.write('accepted connection')
while True:
data = conn.recv( 1024 )
if not data:
break
else:
logger.error ("-" * 20)
logger.error(data)
if "DONE" == data:
break
conn.close()