Log Handler - Python Programming Exercise

In this exercise, you will develop a Python program with a class called Logger, which includes a static method called log. This exercise is perfect for practicing class definition, method implementation, and file handling in Python. By implementing this class, you will gain hands-on experience in handling class definitions, method implementation, and file handling in Python. This exercise not only reinforces your understanding of object-oriented programming but also helps you develop efficient coding practices for managing user interactions.

 Category

Managing Files

 Exercise

Log Handler

 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

 Copy 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

 More Python Programming Exercises of Managing Files

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  More

    In this exercise, you will develop a Python program that mimics the behavior of the Unix "more" command. This exercise is perfect for practicing file handling,...

  •  Text Modifier

    In this exercise, you will develop a Python program that reads a text file, replaces specified words, and saves the modified content into a new file. This exercise...

  •  Count characters in a text file

    In this exercise, you will develop a Python program that counts how many times a specific character appears in a given file (of any type). This exercise is per...

  •  Binary File Reading (BMP Example)

    In this exercise, you will develop a Python program that verifies if a BMP image file is valid by checking its header. This exercise is perfect for practicing ...

  •  Saving Data to a Binary File

    In this exercise, you will develop a Python program that prompts the user to enter their name, age (as a byte), and birth year (as an integer), then saves this inform...

  •  Reverse the contents of a text file

    In this exercise, you will develop a Python program that inverts the contents of a text file. This exercise is perfect for practicing file handling, loops, and...