Maintaining Logging and/or stdout/stderr in Python Daemon

后端 未结 3 2130
长情又很酷
长情又很酷 2020-12-14 19:02

Every recipe that I\'ve found for creating a daemon process in Python involves forking twice (for Unix) and then closing all open file descriptors. (See http://www.jejik.com

3条回答
  •  不知归路
    2020-12-14 19:15

    You can simplify the code for this if you set up your logging handler objects separately from your root logger object, and then add the handler objects as an independent step rather than doing it all at one time. The following should work for you.

    import daemon
    import logging
    
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    fh = logging.FileHandler("./foo.log")
    logger.addHandler(fh)
    
    context = daemon.DaemonContext(
       files_preserve = [
          fh.stream,
       ],
    )
    
    logger.debug( "Before daemonizing." )
    context.open()
    logger.debug( "After daemonizing." )
    

提交回复
热议问题