Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 format, while being able to temporarily add information about some file being read (like its name); the message format should revert to its default when the file is not being read anymore. The program that produces the messages is not aware of what file is being read, so it would be nice if its message automatically included the relevant file name (the error message would be: "ERROR while reading file ***: …" instead of "ERROR: …").

like image 872
Eric O Lebigot Avatar asked Jul 27 '11 16:07

Eric O Lebigot


People also ask

How do I change the logger format in Python?

stderr ) and a default format for the displayed message before delegating to the root logger to do the actual message output. You can change this by passing a format string to basicConfig() with the format keyword argument. For all options regarding how a format string is constructed, see Formatter Objects.

What is StreamHandler in python logging?

StreamHandler. The StreamHandler class, located in the core logging package, sends logging output to streams such as sys. stdout, sys. stderr or any file-like object (or, more precisely, any object which supports write() and flush() methods).


1 Answers

Here is a simple solution, that can be deduced from Vinay Sajip's own HOWTO; it basically updates the logging formatter with setFormatter():

import logging

logger = logging.getLogger()  # Logger
logger_handler = logging.StreamHandler()  # Handler for the logger
logger.addHandler(logger_handler)

# First, generic formatter:
logger_handler.setFormatter(logging.Formatter('%(message)s'))
logger.error('error message')  # Test

# New formatter for the handler:
logger_handler.setFormatter(logging.Formatter('PROCESSING FILE xxx - %(message)s'))
logger.error('error message')  # Test

This correctly produces:

error message
PROCESSING FILE xxx - error message

(where xxx can be set dynamically to the file being processed, as asked for in the question).

like image 176
Eric O Lebigot Avatar answered Oct 01 '22 05:10

Eric O Lebigot