Python registration time since the program started

I use the logging module to create logs and output. Instead of using $(asctime)s in logging.Formatter , is there a good way to register a timestamp relative to creating a logger?

+7
python logging
source share
2 answers

You can write your own formatter:

 from datetime import timedelta import logging import time class ElapsedFormatter(): def __init__(self): self.start_time = time.time() def format(self, record): elapsed_seconds = record.created - self.start_time #using timedelta here for convenient default formatting elapsed = timedelta(seconds = elapsed_seconds) return "{} {}".format(elapsed, record.getMessage()) #add custom formatter to root logger for simple demonstration handler = logging.StreamHandler() handler.setFormatter(ElapsedFormatter()) logging.getLogger().addHandler(handler) log = logging.getLogger('test') log.error("Message 1") time.sleep(5) log.error("Message 2") 

Your question relates to the elapsed time from the "beginning of the program", as well as to the "creation of the registrar", which can mean different things.

This will measure the time elapsed since the CustomFormatter , which you could close when the program started or when creating the log.

+5
source share

Using the %(relativeCreated)d field in a regular Formatter format Formatter displays the milliseconds that have passed since the logging module was loaded. Although the milliseconds may not be what you want, there is no need for additional coding.

+4
source share

All Articles