Skip to content

How to Fix Python Logging Not Writing to File

DodaTech 2 min read

In this tutorial, you'll learn about How to Fix Python Logging Not Writing to File. We cover key concepts, practical examples, and best practices.

The Problem

You set up Python's logging module but no output appears in the log file, either because the handler level is too restrictive, the path is wrong, or the logger is not configured before use. These issues are especially common when importing modules that configure logging before your code runs.

Quick Fix

Configure a File Handler with the Correct Level

python3 -c "
import logging

logging.basicConfig(
    filename='app.log',
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logging.info('This message goes to the file')
"

basicConfig() only works if called before any other logging call. If a logger has already been used, it silently does nothing, which is why configuration placement matters.

Check the File Path and Permissions

python3 -c "
import logging, os

log_path = '/var/log/app.log'
try:
    logging.basicConfig(filename=log_path, level=logging.INFO)
    logging.info('test')
except PermissionError as e:
    print(f'Cannot write: {e}')
    log_path = os.path.expanduser('~/app.log')
    logging.basicConfig(filename=log_path, level=logging.INFO)
    logging.info('Wrote to home directory instead')
"
# Cannot write: [Errno 13] Permission denied: '/var/log/app.log'

Always verify the target directory exists and is writable. Use os.path.expanduser() for user-writable paths and check directory permissions with os.access().

Verify Handler Is Attached

python3 -c "
import logging

logger = logging.getLogger('myapp')
logger.setLevel(logging.DEBUG)

handler = logging.FileHandler('debug.log')
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)

logger.debug('Debug message')
print(f'Handlers: {logger.handlers}')
print(f'Level: {logging.getLevelName(logger.level)}')
"
# Handlers: [<FileHandler debug.log>]
# Level: DEBUG

Explicitly create a FileHandler and attach it to the logger to bypass basicConfig limitations. This gives you fine-grained control over each handler's level and format.

Verify Your Python Environment

python3 --version
# Python 3.10.12
pip list | grep requests
# requests            2.31.0

Check your Python version and installed packages before debugging. Many errors are caused by version mismatches between development and production environments. Using a virtual environment with pinned dependencies prevents these surprises.

Additional Troubleshooting

# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"

If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.

Use RotatingFileHandler for Production

python3 -c "
import logging
from logging.handlers import RotatingFileHandler
handler = RotatingFileHandler('app.log', maxBytes=1024*1024, backupCount=5)
logging.basicConfig(handlers=[handler], level=logging.INFO)
logging.info('Production logging configured')
"

RotatingFileHandler automatically rotates log files when they reach a certain size, preventing disk space issues. The backupCount parameter controls how many old log files are kept.

Prevention

  • Configure logging at the very top of your script before importing modules that may log
  • Use logging.getLogger(__name__) and add handlers explicitly for fine-grained control
  • Check that the logging level allows your messages (e.g., INFO is above DEBUG)
  • Run with a debug logger to a file first, then adjust levels for production

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro