Uwaga: Craig McDaniel's solution jest wyraźnie lepszy.
logging.Formatter za formatTime
metoda wygląda następująco:
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
Wskazówka przecinek w "%s,%03d"
. Nie można tego naprawić, określając wartość datefmt
, ponieważ obiekty te nie rejestrują milisekund.
Jeśli zmienimy definicję ct
aby to datetime
obiekt zamiast struct_time
, to (przynajmniej w nowoczesnych wersjach Pythona) możemy nazwać ct.strftime
i wtedy możemy użyć %f
do formatu mikrosekund:
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.
lub, aby uzyskać milisekund zmienić przecinek kropką dziesiętną, a pominąć datefmt
argument:
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.
Może zmiana ustawienia może pomóc? – pajton
@ pajton - w poniższym linku jest napisane: "Informacje o lokalizacji nie są używane przez asctime()" - http://docs.python.org/library/time.html#time.asctime – Jonathan
'% f' nie działa na pytonie 2.7.9 lub 3.5.1 albo –