Search code examples
pythonloggingconfiguration-files

Is there a way to configure a Python logging formatter via config file to log time as Unix timestamp?


I'm writing a central logging configuration file for a dozen or so Python components and I need one specific logger to log time in the UNIX time format (either milliseconds or seconds with fractions, both is good).

Is there a way to configure a formatter in the config file, to output %(asctime)s like that? I'm trying to avoid having to monkey-patch a Formatter instance in multiple independent Python scripts, and it's unfeasible to post-process the log-file.

Related: Python logging: override log time


Solution

  • 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).