Tenga en cuenta Craig McDaniel's solution es claramente mejor.
método de logging.Formatter formatTime
se ve así:
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
Aviso la coma en "%s,%03d"
. Esto no se puede solucionar especificando un datefmt
porque ct
es un time.struct_time
y estos objetos no registran milisegundos.
Si cambiamos la definición de ct
para que sea un objeto datetime
en lugar de un struct_time
, entonces (al menos con las versiones modernas de Python) podemos llamar ct.strftime
y entonces podemos utilizar %f
a microsegundos formato:
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.
O, para obtener milisegundos, cambiar la coma a un punto decimal, y omitir el argumento 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.
¿Tal vez cambiar la configuración regional podría ayudar? – pajton
@ pajton - en el siguiente enlace dice "La información de configuración regional no es utilizada por asctime()" - http://docs.python.org/library/time.html#time.asctime – Jonathan
'% f' no funciona en python 2.7.9 o 3.5.1 ya sea –