I want to add the userdefined variable to the log format using ContextFiltering. My code is as follows:
import logging
import logging.handlers
CMDID='TEST'
class ContextFilter(logging.Filter):
def filter(self,record):
record.CMDID=CMDID
return True
FORMAT='%(asctime)s [%(CMDID)s] - %(message)s'
logger=logging.getLogger("Test")
fh=logger.handlers.RotatingFileHandler("testing.log",maxBytes=1024,backupCount=5)
fh.setlevel(logging.DEBUG)
fh.setFormatter(logging.Formatter(FORMAT))
logger.addHandler(fh)
logger.addFilter(ContextFilter())
logger.warning("WTH")
When I do not use filehandler and just use basicConfig for formatting, then the code works fine. But when I add a rotating file handler, I get an error
Traceback (most recent call last):
Line 16, in <module>
fh=logger.handlers.RotatingFileHandler("testing.log",maxBytes=1024,backupCount=5)
AttributeError: 'list' object has no attribute 'RotatingFileHandler'
Now I also tried to use the LoggerAdapters class for this, but it also gives rise to strange errors which, upon further investigation, I discovered that there might be some problems with its documentation.
Can someone help me in solving this problem and offer me a way to effectively add user-defined contextual information in my logger using this FileHandler.
P.S. , python,