I'm logging to a file and sysout using logging
in Python 3.8
Currently, the logs go to both the file and sysout. But I want to log to either of them conditionally.
My current code is:
logpath = constants.LOGS_LOCATION
fileHandler = RotatingFileHandler(logpath, maxBytes = 500000, backupCount = 10)
localLogFormatter = logging.Formatter("%(asctime)s [%(levelname)s] %(filename)s - %(funcName)s - %(message)s")
fileHandler.setFormatter(localLogFormatter)
stdoutHandler = logging.StreamHandler(sys.stdout)
formatter = MyJsonFormatter()
stdoutHandler.setFormatter(formatter)
logging.root.handlers = []
logging.basicConfig(
level=logging.INFO,
handlers=[
fileHandler,
stdoutHandler
]
)
So when I do:
logging.info("goes to both file and sysout")
The above goes to both file and sysout, but I want the log to either go to file or sysout depending on my business requirement.
How can I achieve this? Can it be done parameterized or different loggers?