请注意,[ 克雷格·麦克丹尼尔(CraigMcDaniel)的解决方案显然更好。
这也应该工作:
logging.Formatter(fmt='%(asctime)s.%(msecs)03d',datefmt='%Y-%m-%d,%H:%M:%S')
logging.Formatter的
formatTime方法如下所示:
def formatTime(self, record, datefmt=None): 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) return s
请注意中的逗号
"%s,%03d"。不能通过指定a来解决此问题,
datefmt因为
cta是,
time.struct_time并且这些对象不记录毫秒。
如果我们更改的定义
ct以使其成为
datetime对象而不是
struct_time,那么(至少在现代版本的Python中)可以调用
ct.strftime,然后可以用来
%f设置微秒的格式:
import loggingimport datetime as dtclass MyFormatter(logging.Formatter): converter=dt.datetime.fromtimestamp def formatTime(self, record, datefmt=None): ct = self.converter(record.created) if datefmt: s = ct.strftime(datefmt) else: t = ct.strftime("%Y-%m-%d %H:%M:%S") s = "%s,%03d" % (t, record.msecs) return slogger = logging.getLogger(__name__)logger.setLevel(logging.DEBUG)console = logging.StreamHandler()logger.addHandler(console)formatter = MyFormatter(fmt='%(asctime)s %(message)s',datefmt='%Y-%m-%d,%H:%M:%S.%f')console.setFormatter(formatter)logger.debug('Jackdaws love my big sphinx of quartz.')# 2011-06-09,07:12:36.553554 Jackdaws love my big sphinx of quartz.
或者,要获得毫秒数,请将逗号更改为小数点,然后省略
datefmt参数:
class MyFormatter(logging.Formatter): converter=dt.datetime.fromtimestamp def formatTime(self, record, datefmt=None): ct = self.converter(record.created) if datefmt: s = ct.strftime(datefmt) else: t = ct.strftime("%Y-%m-%d %H:%M:%S") s = "%s.%03d" % (t, record.msecs) return s...formatter = MyFormatter(fmt='%(asctime)s %(message)s')...logger.debug('Jackdaws love my big sphinx of quartz.')# 2011-06-09 08:14:38.343 Jackdaws love my big sphinx of quartz.
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)