Python Simple Logging System Example
Build a small Python logging system that writes messages with timestamps and levels like INFO and ERROR. This example helps beginners understand how to record program activity in a simple, practical way.
If you want a quick working version first, use this:
from datetime import datetime
def log_message(level, message, filename="app.log"):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
line = f"[{timestamp}] {level}: {message}\n"
with open(filename, "a", encoding="utf-8") as file:
file.write(line)
log_message("INFO", "Program started")
log_message("ERROR", "Something went wrong")
print("Messages written to app.log")
This version appends log messages to a file so old messages are not erased.
What this example does
This script creates a very simple logging system.
It:
- Creates a reusable function for writing log messages
- Adds a timestamp to each message
- Stores logs in a text file
- Uses simple log levels such as
INFOandERROR
Here is the full example again:
from datetime import datetime
def log_message(level, message, filename="app.log"):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
line = f"[{timestamp}] {level}: {message}\n"
with open(filename, "a", encoding="utf-8") as file:
file.write(line)
log_message("INFO", "Program started")
log_message("INFO", "Loading user data")
log_message("ERROR", "Could not connect to server")
print("Messages written to app.log")
How it works
datetime.now()gets the current date and timestrftime("%Y-%m-%d %H:%M:%S")turns that date and time into readable text- The formatted log line is stored in
line open(filename, "a", encoding="utf-8")opens the file in append modefile.write(line)adds the message to the file
If you are new to writing files, see how to write to a file in Python and how to append to a file in Python.
Why logging is useful
Logging helps you keep a record of what your program did.
This is useful because it:
- Helps you see what your program did
- Makes debugging easier
- Lets you keep a record of errors
- Is more useful than
print()when you want saved output
For example, print() only shows text in the terminal while the program is running. A log file stays on your computer, so you can check it later.
Core parts of the script
These are the most important parts of the example:
datetime.now()gets the current date and timestrftime()formats the timestamp as readable textopen(filename, "a")opens the file in append mode- The log function keeps the code organized and reusable
The logging function
from datetime import datetime
def log_message(level, message, filename="app.log"):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
line = f"[{timestamp}] {level}: {message}\n"
with open(filename, "a", encoding="utf-8") as file:
file.write(line)
Key lines:
levelis a label such asINFOorERRORmessageis the text you want to savefilename="app.log"gives the function a default log file name\nadds a newline so each log entry appears on its own line
If you want to understand open() better, see Python open() function explained.
Step-by-step build order
A good way to build this script is:
- Import
datetime - Create a function that accepts a level and message
- Build the log line as a string
- Open the log file in append mode
- Write the line to the file
- Call the function with different message types
Here is the same process as code:
from datetime import datetime
def log_message(level, message, filename="app.log"):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
line = f"[{timestamp}] {level}: {message}\n"
with open(filename, "a", encoding="utf-8") as file:
file.write(line)
log_message("INFO", "Program started")
log_message("ERROR", "File not found")
This keeps the script simple and easy to reuse in other small programs.
Expected output in the log file
Lines are saved in app.log.
Each line includes:
- Date
- Time
- Level
- Message
Example:
[2026-04-22 10:30:15] INFO: Program started
[2026-04-22 10:30:16] ERROR: Something went wrong
To run the script:
python script.py
To check the log file on macOS or Linux:
cat app.log
To check the log file on Windows Command Prompt:
type app.log
To see the full path of the log file:
python -c "from pathlib import Path; print(Path('app.log').resolve())"
Easy ways to improve this example
Once the basic version works, you can extend it.
Easy improvements include:
- Add more log levels such as
WARNINGorDEBUG - Print the message to the screen and save it to the file
- Use a different file name for each day
- Wrap risky code in
try-exceptand log errors
Here is a slightly improved version that prints and logs at the same time:
from datetime import datetime
def log_message(level, message, filename="app.log"):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
line = f"[{timestamp}] {level}: {message}"
print(line)
with open(filename, "a", encoding="utf-8") as file:
file.write(line + "\n")
log_message("INFO", "User opened the program")
log_message("WARNING", "Input was empty")
log_message("ERROR", "Could not save file")
If you want to handle errors while logging program problems, see how to handle exceptions in Python and the Python error handling example script.
Common mistakes
These are common reasons beginners think the script is not working:
- Opening the file in write mode instead of append mode, which erases old logs
- Forgetting the newline character so all logs appear on one line
- Using a file path that does not exist
- Misspelling the filename and checking the wrong file
- Expecting logging to work without calling the function
Example of a common mistake
This version uses write mode:
with open("app.log", "w", encoding="utf-8") as file:
file.write("This will replace the old file contents.\n")
Mode "w" creates a new file or overwrites an existing file.
If you want to keep old log entries, use "a" instead:
with open("app.log", "a", encoding="utf-8") as file:
file.write("This will be added to the end of the file.\n")
For a broader introduction to files, see Python file handling basics: read and write.
FAQ
What is the difference between logging and print()?
print() shows output on the screen. Logging saves messages so you can review them later.
Why use append mode when opening the file?
Append mode adds new messages to the end of the file instead of deleting old ones.
Can I log errors only?
Yes. You can call the function only when an error happens, but logging normal steps can also help with debugging.
Do I need the logging module for this example?
No. This page shows a simple beginner-friendly version. The standard logging module is more powerful but more advanced.
See also
- How to write to a file in Python
- How to append to a file in Python
- Python file handling basics: read and write
- Python open() function explained
- How to handle exceptions in Python
- Python error handling example script
Try extending this script in one of your own projects by logging user actions, important steps, or errors.