I'm facing an issue with logging in my Python application. I've set up logging to capture errors and write them to a file using a RotatingFileHandler, but for some reason, errors aren't getting logged to the file as expected.
My logger config:
# In logger_config.py
import logging
from logging.handlers import RotatingFileHandler
def setup_logging(name: str):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
log_msg = """
===========
%(asctime)s - %(name)s - %(levelname)s - %(filename)s:
%(message)s
===========
"""
formatter = logging.Formatter(log_msg)
file_handler = RotatingFileHandler(
'logs/app.log', maxBytes=1000000, backupCount=5)
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(formatter)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(console_handler)
return logger
Here is where I use logger instance:
# In my_script.py
from .logger_config import setup_logging
logger = setup_logging(__name__)
async def CallStep1(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""
STEP 1: Choosing the Location
"""
try:
# Code...
except Exception as e:
logger.error(f"An error occurred in CallStep1: {e}", exc_info=True) # this gets logged in the console but its not getting saved in the file
- I've defined a logger configuration function that sets up the logger with a RotatingFileHandler and a StreamHandler to output logs to the console.
- The logger is instantiated using the logging.getLogger(name) method.
- I've ensured that the log level is set to DEBUG and the file handler's level is set to ERROR.
- Despite these configurations, errors are not being written to the log file.
I've verified the following:
- File permissions for the log directory are set correctly, and the process has write access.
- There are no exceptions being raised during the logging process itself.
- Logging calls are correctly using the logger instance and the appropriate logging level.