At the interview, you may be asked about how you would develop a logger . The question is quite interesting and allows you to check not only the syntactic constructions of the C# language, but also how do you thinking during the development.
The main Requirements for Logger
- The logger must be able to write to the console
- The logger must be able to write to a file
- The logger must be able to write to the console and to a file simultaneously
Let’s write a logger one by one with a few comments.
Create Interface
The correct and logical solution would be to define an interface . In our case, there will be one method Log with one parameter message.
public interface ILogger { void Log(string message); }
Create Logger to Console
Implementation for the Console logger .
public class ConsoleLogger : ILogger { public void Log(string message) { Console.WriteLine(message); } }
Create Logger to the File
Here is a simple implementation for the File Logger :
public class FileLogger : ILogger { const string path = "myLogFile1.log"; public void Log(string message) { File.AppendAllText(path, message); } }
Write logs to the Console and File simultaneously
Here is an example of the aggregated logger:
public class MultipleLogger: ILogger { private readonly ILogger[] _loggers; public MultipleLogger(params ILogger[] loggers) { _loggers = loggers; } public void Log(string Message) { foreach (var logger in _loggers) { logger.Log(Message); } } }
Now using the MultipleLogger you can write logs in files and console . You just need to declare:
var multipleLogger = new MultipleLogger(new ConsoleLogger(), new FileLogger());
Such a solution will show the correct approach to this task. And you will earn points for the interview 😎
You may also be interested to read my next articles: