当前位置:   article > 正文

python logging 毫秒级别的时间打印_pycharm logging打印毫秒级时间

pycharm logging打印毫秒级时间

需要查看代码性能,所以需要毫秒级别的打印。但是,在logging包中,查了源码之后确认使用的是time包的datefmt。而查看Python的doc文档,在time包中并没有提供毫秒的datefmt,所以,只能重写logging中取时间的函数。如下:


  1. class Formatter(logging.Formatter):
  2. def formatTime(self, record, datefmt=None):
  3. """
  4. Return the creation time of the specified LogRecord as formatted text.
  5. This method should be called from format() by a formatter which
  6. wants to make use of a formatted time. This method can be overridden
  7. in formatters to provide for any specific requirement, but the
  8. basic behaviour is as follows: if datefmt (a string) is specified,
  9. it is used with time.strftime() to format the creation time of the
  10. record. Otherwise, the ISO8601 format is used. The resulting
  11. string is returned. This function uses a user-configurable function
  12. to convert the creation time to a tuple. By default, time.localtime()
  13. is used; to change this for a particular formatter instance, set the
  14. 'converter' attribute to a function with the same signature as
  15. time.localtime() or time.gmtime(). To change it for all formatters,
  16. for example if you want all logging times to be shown in GMT,
  17. set the 'converter' attribute in the Formatter class.
  18. """
  19. ct = self.converter(record.created)
  20. if datefmt:
  21. s = time.strftime(datefmt, ct)
  22. else:
  23. #t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
  24. #s = "%s,%03d" % (t, record.msecs)
  25. s = str(datetime.datetime.now())
  26. return s


此处,在datefmt为None的时候,使用datetime包中的时间替代。

之后,只要在实例化Formater的时候使用该类,并设置datefmt为None即可。

 formatter = Formatter(fmt, datefmt=None)



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/512765
推荐阅读
相关标签
  

闽ICP备14008679号