0

I'm working on converting to the logging library for all my logging, but I've been stuck on this step for a while. I typically log to the console with some color code escape sequences for formatting. This works well in the console, but not in the log files, which shouldn't have any escape sequences. Therefore, I have a function that trims the escape sequences. However, I can't figure out how to link that function to the formatter that I use for console outputs.

Here's what I have for logging setup:

    file_formatter = new_logging.Formatter(log_file_format)
    file_handler = logging.FileHandler(output_path)
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(file_formatter)
    logging.getLogger().addHandler(file_handler)

    console_formatter = logging.Formatter(log_console_format)
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(console_formatter)
    logging.getLogger().addHandler(console_handler)

Essentially, my goal is to automatically run a function remove_escape_sequences(log_string) as part of the file_formatter. Right now it's just set to be a string with placeholders, '%(asctime)s %(levelname)8s: "%(name)24s" - %(message)s'. How can I do this?

Ian
  • 5,704
  • 6
  • 40
  • 72

1 Answers1

0

Ended up finding the answer on my own:

You can implement a custom processing function into a Formatter by creating a subclass where you override the base format method with a custom one. With the following implementation, the base format method will be called first, after which the custom function will be called on the returned value:

class CustomFormatter(logging.Formatter):
    def format(self, record):
        default_formatted = logging.Formatter.format(self, record)
        return custom_processing_method(default_formatted)

This custom formatter can be treated exactly the same as a standard formatter, including initializing and attaching.

Ian
  • 5,704
  • 6
  • 40
  • 72