python logging 毫秒级别的时间打印
2015-10-23 11:36
483 查看
需要查看代码性能,所以需要毫秒级别的打印。但是,在logging包中,查了源码之后确认使用的是time包的datefmt。而查看Python的doc文档,在time包中并没有提供毫秒的datefmt,所以,只能重写logging中取时间的函数。如下:
此处,在datefmt为None的时候,使用datetime包中的时间替代。
之后,只要在实例化Formater的时候使用该类,并设置datefmt为None即可。
formatter = Formatter(fmt, datefmt=None)
class Formatter(logging.Formatter): def formatTime(self, record, datefmt=None): """ Return the creation time of the specified LogRecord as formatted text. This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, the ISO8601 format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the 'converter' attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the 'converter' attribute in the Formatter class. """ ct = self.converter(record.created) if datefmt: s = time.strftime(datefmt, ct) else: #t = time.strftime("%Y-%m-%d %H:%M:%S", ct) #s = "%s,%03d" % (t, record.msecs) s = str(datetime.datetime.now()) return s
此处,在datefmt为None的时候,使用datetime包中的时间替代。
之后,只要在实例化Formater的时候使用该类,并设置datefmt为None即可。
formatter = Formatter(fmt, datefmt=None)
相关文章推荐
- python笔记
- 【Python】一个python实例:给重要的文件创建备份.摘自crossin-python简明教程
- python下编译py成pyc和pyo
- Python 基础
- python 日志打印
- python中编码问题——unicode, gbk, utf8
- 堆排序python实现
- Python中logging模块的使用
- vim - Run python code in vim editor
- python读写文件,和设置文件的字符编码比如utf-8
- Python函数_参数的多类型传值
- python多进程断点续传分片下载器
- Python中文编码问题
- python unittest
- python基础
- mac python eclipse
- 源码安装python
- windows numpy包安装
- windows下ipython的tab补全,只需安装pyreadline即可.
- Mac下iPython-notebook搭建及使用