Python logging time since start in seconds

Viewed 324

I would like to add the number of seconds my program is up to my logging output.

I've found relativeCreated here but it will give me the milliseconds, e.g. this:

logging.basicConfig(format='{relativeCreated:8.0f}ms {levelname:s} {message:s}', style="{")

Results in

4081ms INFO my message
6012ms INFO another message

But as I expect the running times to be in the hours, I would prefer.

4s INFO my message
6s INFO another message

I tried

logging.basicConfig(format='{relativeCreated / 1000:4.0f}s {levelname:s} {message:s}', style="{")

but this results in

KeyError: 'relativeCreated / 1000'
2 Answers

You can subclass logging.Formatter to modify relativeCreated:

import logging
import time

class RelativeSeconds(logging.Formatter):
    def format(self, record):
        record.relativeCreated = record.relativeCreated // 1000
        return super().format(record)

formatter = RelativeSeconds("%(relativeCreated)ds %(levelname)s %(message)s")

logging.basicConfig()
logging.root.handlers[0].setFormatter(formatter)

logging.error("Test 1")
time.sleep(2)
logging.error("Test 2")

Prints:

0s ERROR Test 1
2s ERROR Test 2

try this:

import time

start_time = time.time()
........
print (str(time.time() - start_time) + ' INFO my message') 

It should return time in [s]

Related