Logger, power line output

I have a logger installed. Something like that:

def initLogger(self): self.logger = logging.getLogger('MyApp') if not self.logger.handlers: hdlr = logging.FileHandler('MyApp.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) self.logger.addHandler(hdlr) self.logger.setLevel(logging.WARNING) 

I want to always print a line in the log when the program starts. But I do not want to register it as a warning. I just want to always have a trace that marks the start of execution. I know that I can switch the level to INFO or DEBUG and call self.logger.info ("Program Start"), but that seems messy. Is there a way to force withdrawal regardless of the registrar level?

thanks

+4
source share
3 answers

The easiest way that comes to mind is to simply write a log message after adding formatting and a handler, but before setting the logger level. If the registration system is fully configured by your program, then no registrar will set the level until you explicitly set it, and therefore all messages will be recorded until you set the level.

Another way is to set a filter instead of setting the log level. A filter can reject all messages below a certain level, unless the message matches the specified template or until you call the filter enable method or some such thing. However, you sacrifice some efficiency; The standard implementation of Logger designed to immediately check the level when any of the logging methods is called, and to discard the message if it is not at a sufficiently high level, while filters are checked later in the process.

If something else outside your code already sets the log level to WARNING , and you cannot control it, then it really isnโ€™t. You will have to either temporarily reset the logger level (which can become messy if you do not use a top-level logger, since you need to check and reset the level on several โ€œgenerationsโ€ of loggers) or set your own Logger subclass before creating any logs. In this case, I would say that it is probably not your responsibility to verify that the logging system works anyway.

+2
source

You can open the file, write your launch message to it, and then transfer it as a stream to StreamHandler .

0
source

I'm not sure if this can be considered an abuse of the logging system, but what about the following:

 logging.addLevelName(100, 'INFO') logging.log(100, 'Program Start') 

This leads to:

 2018-03-06 17:01:29:INFO:root:Program Start 

The highest predefined level, CRITICAL , is set to 50, so 100 for our fake INFO level should be sufficient to ensure that it always appears in the log regardless of the current log level.

(If you prefer to assign the 100th level to another name, for example, START , if you find it strange to have an INFO message when the log level is above this.)

0
source

Source: https://habr.com/ru/post/1500600/


All Articles