I have the following questions about python logging module.
Can I change the format defined in configuration file dynamically from code?
Can one module in my application get its format configured by a config file while other modules get their format and other properties configured through a python script?
I want to add contextual info to my logs but I am using a config file to define logger properties. How can I go about this?
P.S. I can provide some code and application structure if required.
Structure -
1.) Agent - calls logging_setup script to set up logger configuration 2.) Modules
I have a logging_setup script that has the following methods:
logging_setup.py
import logging
import logging.handlers
LOGGER_FORMAT="%(asctime)s %(CMDID)s %(levelname)s %(message)s"
class testFormatter(logging.Formatter):
  def format(self,record):
    record.message=record.getMessage()
    if string.find(self._fmt,"%(asctime)") >= 0:
      record.asctime = self.formatTime(record, self.datefmt)
    if threading.currentThread().getName() in cmdidDict:
      record.CMDID=cmdidDict[threading.currentThread().getName()]
    else:
      record.CMDID="Oda_EnvId"
    return self._fmt % record.__dict__
def initLogging(loggername,newCMDID):
  global CMDID
  global newCMDID
  logger=logger.getLogger(loggername)
  format=testFormatter(LOGGER_FORMAT)
  *set up other config*
So I wanted to set up CMDID variable in my logs dynamically which i achieved by using the testFormatter class and initializing logger with that class. There is a bit more to it but I hope u get the idea.
LOGGER_FORMAT="%(asctime)s %(CMDID)s %(levelname)s"
But now I want to change the log level of logs from the modules themselves keeping the format same throughout. So I decided to create a universal config file that could set up the logging configuration for me throughout the application. My problem is how do I make this config file set the CMDID variable in the format.
config file
[loggers]
keys=root,testModule
[formatters]
keys=generic
[handlers]
keys=fh
[logger_root]
level=DEBUG
handlers=fh
[logger_testModule]
level=ERROR        <<-- setting my log level here
handlers=fh
qualname=testModule
propagate=0
[handler_fh]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=generic
maxBytes=1000
args=('spam.log',)
[formatter_generic]
format=%(asctime)s %(levelname)s %(message)s   <<---This should somehow set CMDID var
    
ConfigParserand read various loglevels at runtime from the configsectionand insert it