Exercise
Logger
Objetive
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"
Example Code
using System;
using System.IO;
public class Logger
{
///
/// Writes a log entry to the specified file.
///
/// The name of the file where the log entry will be appended.
/// The message to log.
public static void Write(string fileName, string message)
{
// Validating inputs
if (string.IsNullOrWhiteSpace(fileName))
{
Console.WriteLine("File name cannot be null or empty.");
return;
}
if (string.IsNullOrWhiteSpace(message))
{
Console.WriteLine("Message cannot be null or empty.");
return;
}
try
{
// Formatting the log message with date and time
string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}";
// Writing the log entry to the file
using (StreamWriter writer = new StreamWriter(fileName, true))
{
writer.WriteLine(logEntry);
}
// Confirming the log was written successfully
Console.WriteLine($"Log entry written: {logEntry}");
}
catch (Exception ex)
{
// Displaying any errors
Console.WriteLine($"Error writing log: {ex.Message}");
}
}
}
public class Program
{
public static void Main()
{
// Testing the logger
Logger.Write("myLog.txt", "This is the first log entry.");
Logger.Write("myLog.txt", "This is another log entry.");
Logger.Write("myLog.txt", "Logging one more message.");
}
}