Writing logs to disk

Catel also supports very lightweight listeners to allow external logging libraries to hook on. To create a listener, first create a new class that implements the ILogListener interface. Next, register it in the LogManager using the LogManager.AddListener method.

The ILogListener has a separate method for each LogEvent, but also has a shared method that is called for each log event. For example, if a debug message is written to the log, both the Write and Debug methods are invoked on the ILogListener.

 Creating the listener

A listener can be created by creating a new class deriving from LogListenerBase.

public class FileLogListener : LogListenerBase
{
    private readonly TextWriter _textWriter;

    public FileLogListener(string fileName)
    {
        Argument.IsNotNullOrWhitespace("fileName", fileName);
        FileName = fileName;

        _textWriter = new StreamWriter(fileName, true);
    }

    public string FileName { get; private set; }

    public override void Write(ILog log, string message, LogEvent logEvent)
    {
        _textWriter.WriteLine(message);
    }
}

Registering the listener

 Last but not least, it is important to register the listener:

LogManager.AddListener(new FileLogListener("<log_file_path>"));