I would like to use the "logging" module in Python to write errors to a log file. However, I want the file to be created only if there are errors. I am using the following code:
import logging
f = 'test.conf'
logger = logging.getLogger("test_logger")
logger.setLevel(logging.INFO)
ch_file = logging.FileHandler("test_logger.conf")
ch_file.setLevel(logging.ERROR)
logger.addHandler(ch_file)
ch_file.close()
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.info("info")
logger.warn("warning")
When logger.error ("error") is uncommented, I expect the file "test_logger.conf" to be made with an error in it. However, when the line is commented out, I found that the test_logger.conf file is still done and empty. How can I make this file NOT done if there are no error messages?
Thank.
source
share