Reputation: 4029
I have a logger set up. Something like this:
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 to the log at program startup. But, I don't want to log it as a warning. I just want to always have a trace that marks the beginning of execution. I know I could switch the level to INFO or DEBUG and call self.logger.info("Program start"), but that seem messy. Is there a way to force output regardless of logger level?
Thanks
Upvotes: 6
Views: 2049
Reputation: 6174
I'm not sure if this might be considered an abuse of the logging system, but what about the following:
logging.addLevelName(100, 'INFO')
logging.log(100, 'Program Start')
This results in:
2018-03-06 17:01:29:INFO:root:Program Start
The highest pre-defined level, CRITICAL
, has a value of 50 so using 100 for our fake INFO
level should be sufficient to ensure that it always appears in the log regardless of the current log level.
(You can if you prefer give level 100 a different name such as START
if you think it's weird having an INFO
message appear when the log level is above that.)
Upvotes: 4
Reputation: 99365
You could open the file, write your startup message to it and then pass it as the stream to a StreamHandler
.
Upvotes: 0
Reputation: 131600
The easiest way that comes to mind is to just write the log message after adding the formatter and handler, but before setting the logger level. If the logging system is configured entirely by your program, then no logger will have a level set until you explicitly set one, and so all messages will be logged until you set the level.
Another way would be to install a filter instead of setting the log level. The filter could reject all messages below a certain level unless the message matches a specified pattern, or until you call a method on the filter to switch it on, or some such thing. By doing this you sacrifice a bit of efficiency, though; the standard implementation of Logger
is built to check the level immediately when any of the logging methods are called, and discard the message if it's not at a high enough level, whereas filters are checked later in the process.
If something else outside your code already sets the logger level to WARNING
, and you can't control that, then there's really no way around it. You will have to either temporarily reset the logger level (which could get messy if you are not using a top-level logger, since you have to check and reset the level on multiple "generations" of loggers), or install your own custom Logger
subclass before any loggers are created. In this case I'd say it's probably not your responsibility to check that the logging system is working anyway.
Upvotes: 2