0

我的脚本很好地记录到一个文件中,直到我尝试将它分叉到后台,此时文件句柄被关闭,即使我使用 filesPreserve。如何以轻量级的方式改进这一点,以便我的记录器在后台运行?

#!/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()
4

1 回答 1

1

你想要的是:

context.files_preserve = [hdlr.stream]

由于 files_preserve 需要一个文件处理程序。

您可以在此处查看更多信息

于 2013-07-29T20:33:47.163 回答