Xin lưu ý giải pháp của Craig McDaniel rõ ràng là tốt hơn.
formatTime
Phương thức của log.Formatter trông như thế này:
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
Chú ý dấu phẩy trong "%s,%03d"
. Điều này không thể được sửa bằng cách chỉ định a datefmt
bởi vì ct
a time.struct_time
và các đối tượng này không ghi lại mili giây.
Nếu chúng ta thay đổi định nghĩa ct
để biến nó thành một datetime
đối tượng thay vì a struct_time
, thì (ít nhất là với các phiên bản hiện đại của Python), chúng ta có thể gọi ct.strftime
và sau đó chúng ta có thể sử dụng %f
để định dạng micro giây:
import logging
import datetime as dt
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
logger = 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.
Hoặc, để có được mili giây, thay đổi dấu phẩy thành dấu thập phân và bỏ qua datefmt
đối số:
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.