How to change the format of logged messages temporarily, in Python?

后端 未结 4 1740
长发绾君心
长发绾君心 2020-12-06 00:33

What is the simplest method for temporarily changing the logging message format, in Python (through the logging module)?

The goal is to have some standard message fo

4条回答
  •  星月不相逢
    2020-12-06 01:13

    There are several ways. Apart from the already documented ones (extra argument to logging calls, LoggerAdapter, Filter) , another way would be to specify a custom formatting class, whose instance you can keep informed about the file being processed. For example:

    class FileProcessingFormatter(logging.Formatter):
        def __init__(self, fmt, datefmt=None, current_file=None):
            super(FileProcessingFormatter, self).__init__(fmt, datefmt)
            self.orig_fmt = fmt
            self.current_file = current_file
    
        def format(self, record):
            if self.current_file is None:
                self._fmt = self.orig_fmt.replace('__FILE_PLACEHOLDER__', '')
            else:
                self._fmt = self.orig_fmt.replace('__FILE_PLACEHOLDER__',
                                ' while processing %r' % self.current_file)
            return super(FileProcessingFormatter, self).format(record)
    

    Instantiate the formatter ...

    f = FileProcessingFormatter('%(levelname)s__FILE_PLACEHOLDER__ %(message)s')
    for h in relevant_handlers:
        h.setFormatter(f)
    

    Process files ...

    f.current_file = fn
    process_file(fn)
    f.current_file = None
    

    This is very simplistic - for example, not for use in threaded environments if file processing is done by different threads concurrently.

    Update: Although the root logger's handlers are accessible via logging.getLogger().handlers, this is an implementation detail that could change. As your requirement is not that basic, you could perhaps use dictConfig() to configure your logging (available via the logutils project for older versions of Python).

提交回复
热议问题