Objective
Develop a Python program with a class called Logger, which includes a static method called log. This method will take a file name and a message as input and append the message to the file. Each log entry should also include the current date and time, making it easier to analyze the log later.
Example usage:
Logger.log("myLog.txt", "This message is logged.")
The log method should ensure the message is saved at the end of the file, and the timestamp should be placed before the message on the same line.
Hint: Explore how to use file handling for appending and how to fetch the current timestamp with datetime.now.
Example Python Exercise
Show Python Code
from datetime import datetime
class Logger:
"""
A class that provides logging functionality.
Includes a static method to log messages to a file with a timestamp.
"""
@staticmethod
def log(file_name, message):
"""
Logs a message to the specified file with the current timestamp.
Appends the message at the end of the file.
Parameters:
file_name (str): The name of the file to which the log will be saved.
message (str): The message to be logged.
"""
try:
# Get the current timestamp in the format YYYY-MM-DD HH:MM:SS
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Open the file in append mode ('a') so we add to the end of the file
with open(file_name, 'a') as file:
# Write the timestamp and the message to the file
file.write(f"{timestamp} - {message}\n")
print(f"Message logged successfully to {file_name}.")
except Exception as e:
print(f"Error logging message: {e}")
# Test the Logger class
if __name__ == "__main__":
# Example usage of the Logger class
Logger.log("myLog.txt", "This message is logged.")
Logger.log("myLog.txt", "Another message for logging.")
Output
Message logged successfully to myLog.txt.
Message logged successfully to myLog.txt.
2024-12-27 14:30:15 - This message is logged.
2024-12-27 14:30:20 - Another message for logging.
Share this Python Exercise