To write logs to a file using Python’s logging
module, you need to add a file handler to your logger.
Here’s a simple example:
import logging
logging.basicConfig(
filename='myapp.log', # Log file name
level=logging.DEBUG, # Log level
format='%(asctime)s %(levelname)s:%(message)s' # Log format
)
logging.info("This will go into myapp.log")
Now, log messages will be written to myapp.log
instead of just printing to the console.
For a detailed guide on logging best practices in Python web apps (including handling multiple handlers, log formats, and real-world scenarios), check out this article:
👉 The Right Way to Maintain Logs in Python Web Apps (Part 1)