Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log time spent from when script started instead of actual time when using python logging module?

Tags:

python

logging

I am looking for a way to change python logging module to display time spent form when the script started instead of current time.

like image 989
sorin Avatar asked Jun 04 '26 09:06

sorin


2 Answers

Use %(relativeCreated)s in your format string, as indicated in the documentation.

Update: You can use normal Python format specifiers to control precision, e.g. %(relativeCreated).0f to show floating point values with zero decimal places.

like image 79
Vinay Sajip Avatar answered Jun 05 '26 23:06

Vinay Sajip


You can subclass logging.Formatter and reimplement formatTime. Something like that:

start_time = datetime.now()

class MyFormatter(logging.Formatter):

    def formatTime(self, record, datefmt=None):
        delta = (datetime.now() - start_time).total_seconds()
        return "{}".format(delta)

And then:

handler = logging.StreamHandler()
fmt = MyFormatter('%(filename)s %(levelname)-8s [%(asctime)s]  %(message)s')
handler.setFormatter(fmt)

log = logging.getLogger('main')
log.addHandler(handler)
log.debug("=)")
like image 42
user2155932 Avatar answered Jun 05 '26 23:06

user2155932



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!