Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Logging: Specifying converter attribute of a log formatter in config file

I'd like to have all timestamps in my log file to be UTC timestamp. When specified through code, this is done as follows:

import logging
import time

myHandler = logging.FileHandler('mylogfile.log', 'a')
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(name)-15s:%(lineno)4s: %(message)-80s')
formatter.converter = time.gmtime

myHandler.setFormatter(formatter)

myLogger = logging.getLogger('MyApp')
myLogger.addHandler(myHandler)

myLogger.setLevel(logging.DEBUG)
myLogger.info('here we are')

I'd like to move away from the above 'in-code' configuration to a config file based mechanism.

Here's the config file section for the formatter:

[handler_MyLogHandler]
args=("mylogfile.log", "a",)
class=FileHandler
level=DEBUG
formatter=simpleFormatter

Now, how do I specify the converter attribute (time.gmtime) in the above section?

Edit: The above config file is loaded thus:

logging.config.fileConfig('myLogConfig.conf')
like image 520
sradhakrishna Avatar asked Aug 27 '12 09:08

sradhakrishna


People also ask

What is logging formatter in Python?

Loggers expose the interface that application code directly uses. Handlers send the log records (created by loggers) to the appropriate destination. Filters provide a finer grained facility for determining which log records to output. Formatters specify the layout of log records in the final output.

What is logging getLogger (__ Name __)?

getLogger(name) is typically executed. The getLogger() function accepts a single argument - the logger's name. It returns a reference to a logger instance with the specified name if provided, or root if not. Multiple calls to getLogger() with the same name will return a reference to the same logger object.


2 Answers

Sadly, there is no way of doing this using the configuration file, other than having e.g. a

class UTCFormatter(logging.Formatter):
    converter = time.gmtime

and then using a UTCFormatter in the configuration.

like image 96
Vinay Sajip Avatar answered Sep 22 '22 16:09

Vinay Sajip


Here Vinay's solution applied to the logging.basicConfig:

import logging
import time

logging.basicConfig(filename='junk.log', level=logging.DEBUG, format='%(asctime)s: %(levelname)s:%(message)s')
logging.Formatter.converter = time.gmtime
logging.info('A message.')
like image 41
Chuck Avatar answered Sep 21 '22 16:09

Chuck