To get Python's logging module to find and load a configuration file, you typically use the fileConfig() function from logging.config. Here's how to do it properly and ensure your config file is found.
✅ Step-by-step Guide
1. Create a Logging Configuration File
Example: logging.ini
[loggers]
keys=root
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[handler_consoleHandler]
class=StreamHandler
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
2. Use fileConfig() in Your Python Script
import logging
from logging.config import fileConfig
import os
# Path to your logging config file
config_path = os.path.join(os.path.dirname(__file__), 'logging.ini')
# Make sure the file exists
if not os.path.exists(config_path):
raise FileNotFoundError(f"Logging config file not found at {config_path}")
# Load the logging config
fileConfig(config_path)
# Now logging is configured
logger = logging.getLogger()
logger.debug("Debug message")
🔍 Tips for Making Sure the Config File Is Found
-
Relative paths can be tricky depending on where you run the script from.
Use os.path.dirname(__file__) to get the directory of the current script:
config_path = os.path.join(os.path.dirname(__file__), 'logging.ini')
-
Absolute paths are more reliable if you're having trouble:
config_path = '/absolute/path/to/logging.ini'
-
You can also use environment variables to define the path:
import os
config_path = os.getenv("LOG_CONFIG_PATH", "default_logging.ini")
📁 Example Folder Structure
project/
│
├── myapp.py
└── logging.ini
In myapp.py, the code above will correctly locate logging.ini.
⚠️ Common Issues
| Problem | Solution |
|---|
File not found | Double-check the path using os.path.exists(config_path) |
NoSectionError | Check your .ini file syntax (e.g., missing [loggers]) |
ImportError | Make sure you imported fileConfig from logging.config |
✅ Alternative: YAML or Dict Config
If you prefer, you can also use YAML format or dictionary-based configs with dictConfig().
Example:
from logging.config import dictConfig
dictConfig({
'version': 1,
'formatters': {
'simple': {'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'simple',
'level': 'DEBUG'
}
},
'root': {
'level': 'DEBUG',
'handlers': ['console']
}
})
Let me know if you'd like an example using YAML or JSON config!