Is there a way to configure the Python protocol formatter through a configuration file to register the time as a Unix timestamp?

I am writing a central logging configuration file for a dozen Python components, and I need one specific logger to record time in UNIX time format (milliseconds or seconds with fractions, both are good).

Is there a way to configure the formatter in the configuration file to output %(asctime)s like this? I am trying to avoid using the monkey-patch instance of Formatter in several independent Python scripts, and it is not possible to post-process the log file.

Related: Writing in Python: redefine registration time

+4
source share
2 answers

Just add

 datefmt = %s 

to the appropriate section of the formatting configuration or calling the formatting constructor, for example:

 [formatter_generic] format = %(asctime)s %(levelname)-5.5s [%(name)s] %(message)s datefmt = %s 

See also logging.Formatter constructor and strftime (3) .

+5
source

I 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() 
0
source

Source: https://habr.com/ru/post/1396267/


All Articles