Mini Project: Log Writer
Exit
Mini Project: Log Writer
Build a log writer that appends timestamped entries to a file
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
What you will build
A write_log() function that appends a timestamped entry to a log file every time you call it.
Example output
After three calls, app.log contains:
[2024-01-15 10:30] Application started
[2024-01-15 10:30] User logged in
[2024-01-15 10:30] Request processedDesign
| Function | Purpose |
|---|---|
write_log(filename, message) | Append [timestamp] message to the file |
Note on timestamps
In production code, you would use datetime.now() from the datetime module to get the current time. This demo uses a hardcoded timestamp so the output is always the same.
Instructions
Build the log writer function.
- Define a function named
write_logthat takesfilenameandmessage. Inside, create a variable namedtimestampand assign it"2024-01-15 10:30". - Still inside the function, open
filenamein append mode usingwith open(filename, "a") as file:. Inside the block, callfile.write(f"[{timestamp}] {message}\n"). - Call
write_log("app.log", "Application started"). - Call
write_log("app.log", "User logged in"). - Call
write_log("app.log", "Request processed"). - Call
print("app.log updated with 3 entries.").
# Step 1: Define write_log(filename, message) with a hardcoded timestamp # Step 2: Open filename in append mode and write [timestamp] message # Step 3: Log "Application started" # Step 4: Log "User logged in" # Step 5: Log "Request processed" # Step 6: Print confirmation
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding