Python logging time since start of program

Using %(relativeCreated)d field in a conventional Formatter format string will display the milliseconds elapsed since the logging module was loaded. While milliseconds might not be what you want, there's no additional coding required.


You could 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 refers to the elapsed time from the 'start of program' as well as 'creation of logger' which could mean different things.

This will measure the time elapsed from the creation of CustomFormatter which you could do close to the start of the program or when a logger is created.

Tags:

Python

Logging