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 processed

Design

FunctionPurpose
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.

  1. Define a function named write_log that takes filename and message. Inside, create a variable named timestamp and assign it "2024-01-15 10:30".
  2. Still inside the function, open filename in append mode using with open(filename, "a") as file:. Inside the block, call file.write(f"[{timestamp}] {message}\n").
  3. Call write_log("app.log", "Application started").
  4. Call write_log("app.log", "User logged in").
  5. Call write_log("app.log", "Request processed").
  6. Call print("app.log updated with 3 entries.").