赞
踩
需要查看代码性能,所以需要毫秒级别的打印。但是,在logging包中,查了源码之后确认使用的是time包的datefmt。而查看Python的doc文档,在time包中并没有提供毫秒的datefmt,所以,只能重写logging中取时间的函数。如下:
- 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)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。