Does python logging.handlers.RotatingFileHandler allow creation of a group writable log file?

前端 未结 7 564
太阳男子
太阳男子 2021-01-31 08:40

I\'m using the standard python (2.5.2) logging module, specifically the RotatingFileHandler, on a linux system. My application supports both a command-line interfa

7条回答
  •  北海茫月
    2021-01-31 09:04

    I resorted to scanning the logging.handlers module and was unable to see any way to specify a different file permissions mode. So, I have a solution now based on extending the RotatingFileHandler as a custom handler. It was fairly painless, once I found some nice references to creating one. The code for the custom handler is below.

    class GroupWriteRotatingFileHandler(handlers.RotatingFileHandler):
    
        def doRollover(self):
            """
            Override base class method to make the new log file group writable.
            """
            # Rotate the file first.
            handlers.RotatingFileHandler.doRollover(self)
    
            # Add group write to the current permissions.
            currMode = os.stat(self.baseFilename).st_mode
            os.chmod(self.baseFilename, currMode | stat.S_IWGRP)
    

    I also discovered that to reference the custom handler from a logging config file, I had to bind my module to the logging namespace. Simple to do, but annoying.

    from mynamespace.logging import custom_handlers
    logging.custom_handlers = custom_handlers
    

    References I found useful: binding custom handlers and creating custom handlers

提交回复
热议问题