Is there a way to configure a Python logging formatter via config file to log time as Unix timestamp?
Just add
datefmt = %s
to your corresponding formatter config section or formatter constructor call, e.g.:
[formatter_generic]
format = %(asctime)s %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %s
See also logging.Formatter
constructor and strftime(3).
I have just found the following solution:
import logging
class UnixTimeStampFormatter(logging.Formatter):
def formatTime(self, record, datefmt = None):
return "{0:.6f}".format(record.created)
def main():
logChannel = logging.StreamHandler()
logChannel.setFormatter(UnixTimeStampFormatter("%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s"))
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().addHandler(logChannel)
logging.debug('hello');
if __name__ == "__main__":
main()