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

痴心易碎 提交于 2021-02-19 04:32:07

问题


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 .

  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 ).




回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!