Python logging daemon destroys file handle

时光毁灭记忆、已成空白 提交于 2019-12-06 15:23:23

问题


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()

回答1:


What you want is:

context.files_preserve = [hdlr.stream]

Since files_preserve expects a file handler.

You can see more information here



来源:https://stackoverflow.com/questions/14758299/python-logging-daemon-destroys-file-handle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!