0
0
PythonHow-ToBeginner · 3 min read

How to Log to File in Python: Simple Guide with Examples

Use Python's logging module to log messages to a file by configuring a FileHandler. Set up the logger with logging.basicConfig(filename='file.log', level=logging.INFO) to write logs to a file.
📐

Syntax

The basic syntax to log to a file uses the logging.basicConfig function with the filename parameter to specify the log file. The level parameter sets the minimum severity of messages to log.

  • filename: path to the log file.
  • level: logging level like DEBUG, INFO, WARNING, etc.
  • format: optional, defines the log message format.
python
import logging

logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.info('This is an info message')
💻

Example

This example shows how to log different levels of messages to a file named app.log. It demonstrates logging an info message and an error message.

python
import logging

logging.basicConfig(filename='app.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

logging.debug('Debug message: Starting the program')
logging.info('Info message: Program is running')
logging.warning('Warning message: Low disk space')
logging.error('Error message: An error occurred')
logging.critical('Critical message: System failure')

print('Logging complete. Check app.log file.')
Output
Logging complete. Check app.log file.
⚠️

Common Pitfalls

Common mistakes when logging to a file include:

  • Not setting the filename in basicConfig, so logs go to the console instead.
  • Calling basicConfig multiple times, which has no effect after the first call.
  • Not setting an appropriate logging level, causing important messages to be missed.
  • Forgetting to flush or close the log file when using custom handlers.
python
import logging

# Wrong: basicConfig called twice, second call ignored
logging.basicConfig(filename='first.log', level=logging.INFO)
logging.basicConfig(filename='second.log', level=logging.DEBUG)  # Ignored

logging.info('This will go to first.log only')

# Right way: configure once
# Note: basicConfig can only be called once per session
# To change configuration, restart the program or use handlers
📊

Quick Reference

Summary tips for logging to a file in Python:

  • Use logging.basicConfig(filename='file.log', level=logging.LEVEL) to set up file logging quickly.
  • Choose the right level to control what messages are saved.
  • Use format to customize log message appearance.
  • Call basicConfig only once at the start of your program.
  • Check the log file path and permissions if logs do not appear.

Key Takeaways

Use logging.basicConfig with filename to log messages to a file.
Set the logging level to control which messages are recorded.
Call basicConfig only once; multiple calls have no effect.
Customize log message format for clarity and detail.
Check file path and permissions if logs are missing.