Python logging - 1
Python's logging module is a powerful tool for tracking events in applications. It provides flexibility in handling log messages and directing them to different outputs, such as files, consoles, or external monitoring services. Here’s a structured way to explore Python logging:
1.Basics of Python Logging
Python’s built-in logging module allows you to log messages with different severity levels.
For example:
import logging
# Configure basic logging
logging.basicConfig(
filename="app.log", # Logs will be saved in 'app.log'
filemode="w", # Overwrites the file each run
format="%(asctime)s - %(levelname)s - %(message)s",
level=logging.DEBUG # Set log level
)
# Generate log messages
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
logging.critical("This is a critical message")
print("Logging completed. Check 'app.log' for output.")2️⃣ Run the Script
Open a terminal or command prompt and navigate to the folder where the file is saved.
Run the script with:
or, if using Python 3:
3️⃣ Check the Output
Console Output
Since we are only logging to a file (not the console), the terminal output will be:
File Output (app.log)
Open the app.log file in any text editor, and you’ll see:
2. Configuring Log Output
You can specify where logs should be written using basicConfig():
Then, when you run the script, the log messages will appear in the terminal:
5️⃣ Logging to Both Console and File
Modify your script to send logs to both console and file:
Output
📌 Terminal (console) will only show WARNING, ERROR, and CRITICAL messages:
📌 app.log file will contain all log messages:
Last updated