1

I have a tcp server with Twisted, and each client has a log file. So I inherit from twisted.logger.Logger.

from twisted.logger import Logger, textFileLogObserver
from twisted.python.logfile import LogFile

class LALogger(Logger):
    logger_root_path = os.path.join(sys.path[0], 'log')

    def __init__(self, log_folder, log_file_name):
        super().__init__(namespace='')
        logger_path = os.path.join(self.logger_root_path, log_folder)
        self.log_file = LogFile(log_file_name + '.log', logger_path,
                            rotateLength=1000000, maxRotatedFiles=5)
        self.observer = textFileLogObserver(
            self.log_file, timeFormat='[%Y-%m-%d %H:%M:%S]')

When the log file came large than 1000000, it should rotate. But sometimes cann't rename the log file. I guess I should close the log file before rotate. How should I do? Thank you.

lakerszhy
  • 11
  • 2

1 Answers1

0

Don't subclass Logger. If you want a Logger with a particular observer, just write a function:

def my_logger():
    observer = textFileLogObserver(...)
    la_logger = Logger(observer=observer)
    return la_logger

If you want to change the log file rotation behavior, you need to change the behavior of LogFile somehow - because that's what actually writes the log file.

Fortunately, LogFile is just an object with a write method.So you can create your own object which implements write any way you like (including whatever special rotation logic you need) and use that instead.

However, LogFile already closes the file before it rotates it. So, investigate further regarding the cause of whatever rotation-related error you're encountering so that you can fix the correct problem.

Jean-Paul Calderone
  • 47,755
  • 6
  • 94
  • 122