'How to implement Serilog Custom Sink outputTemplate parameter
How do I implement outputTemplate that is common to most sinks?
For example this works:
Logger = new LoggerConfigruration()
.WriteTo.Console(outputTemplate: "{Timestamp}{message}")
.CreateLogger();
I want to
Logger = new LoggerConfigruration()
.WriteTo.MySink(outputTemplate: "{Timestamp}{message}")
.CreateLogger();
Where
public class MySink : ILogeventSink
{
private readonly IFormatProvider formatProvider;
private string outputTemplate;
public void Emit(LogEvent logevent)
{
//something here to do with outputTemplate???
}
public MySink(IFormatProvider format, string template)
{
formatProvider = format;
outputTemplate = template;
}
}
Solution 1:[1]
You can use MessageTemplateTextFormatter
from Serilog.Formatting.Display
.
public class MySink : ILogEventSink
{
private readonly MessageTemplateTextFormatter _formatter;
public MySink(IFormatProvider formatProvider, string outputTemplate)
{
_formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);
}
public void Emit(LogEvent logEvent)
{
using var writer = new StringWriter();
_formatter.Format(logEvent, writer);
var message = writer.ToString()
Console.WriteLine(message);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | samuel coutu |