sorin
sorin

Reputation: 170638

How change python logging to display time passed from when the script execution started?

I want to modify the python logging to log the time elapsed from when the script started (or when the logging module was initialized).

000:00 DEBUG bla bla
000:01 ERROR wow! ... this is measured in minutes:seconds

I found the relativeCreated variable in the logging module, but this is givving me millisecond accuracy which would only spam the logs, making harder to see where the time goes or how log it took to run.

How can I do this?

Upvotes: 3

Views: 1549

Answers (3)

Vinay Sajip
Vinay Sajip

Reputation: 99465

You can use a logging.Formatter subclass which gets the relativeCreated from the LogRecord passed to its format method, format it as mins:secs and output it in the format string e.g. using a different placeholder in the format string, such as %(adjustedTime)s:

class MyFormatter(logging.Formatter):
    def format(self, record):
        record.adjustedTime = format_as_mins_and_secs(record.relativeCreated)
        return super(MyFormatter, self).format(record)

where you can define format_as_mins_and_secs to return the formatted relative time.

Upvotes: 7

Ross
Ross

Reputation: 242

I'm not sure you can do this using the logging python module (I could be wrong).

If you need the run-time of the application, though, I would say you should capture the time at application start in a variable (using the time module). Once the time has been captured, you can then pass that variable to the logger to calculate the difference when hitting an error.

Upvotes: -2

Daniel Gurianov
Daniel Gurianov

Reputation: 551

First that pops up in my mind .

  1. Calculate time delta between time script started and time that is now.
  2. Use datetime module for that (do calc to epoh secs and back to timestamp) .
  3. Insert results by loggin module into message section.

I do not put any code for now to inspire you to read more about modules mentioned ).

Upvotes: -3

Related Questions