问题
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?
回答1:
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.
回答2:
First that pops up in my mind .
- Calculate time delta between time script started and time that is now.
- Use datetime module for that (do calc to epoh secs and back to timestamp) .
- 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 ).
回答3:
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.
来源:https://stackoverflow.com/questions/18639387/how-change-python-logging-to-display-time-passed-from-when-the-script-execution