Objective
Create a class Logger, with a static method Write, which will append a certain text to a file: Logger.Write("myLog.txt", "This text is being logged");
It must also include the current date and time before the text (in the same line), so that the log file is easier to analyze.
Hint: find information about "AppendText" and about "DateTime.now"
Write Your C# Exercise
C# Exercise Example
// Importing necessary namespaces for file handling and date/time manipulation
using System;
using System.IO;
public class Logger
{
// Static method to append a log entry to a specified file
public static void Write(string fileName, string message)
{
// Formatting the message with the current date and time
string logEntry = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - " + message;
// Using StreamWriter in append mode to write the log entry to the file
using (StreamWriter writer = File.AppendText(fileName))
{
writer.WriteLine(logEntry); // Writing the formatted log entry to the file
}
// Confirming the log entry has been written to the file
Console.WriteLine("Log entry successfully written to file: " + fileName);
}
}
// Auxiliary class for testing the Logger functionality
public class Program
{
public static void Main()
{
// Example usage of the Logger's Write method
Logger.Write("myLog.txt", "This text is being logged");
// Logging another message to demonstrate multiple entries
Logger.Write("myLog.txt", "Another log entry added");
}
}