In reference to the solution from @Andrew Radford, that solution was working for me only on windows, but not on linux docker environment as expected. Therefore
I have enhanced the solution for messages as well as exceptions.
I have used Environment.NewLine for case matching in Regex which will pick the case based on the hosted environment.
Add following class for Messages.
public class MessageEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (logEvent.MessageTemplate == null)
return;
var logEventProperty = propertyFactory.CreateProperty("EscapedMessage", Regex.Replace(logEvent.MessageTemplate.ToString(), Environment.NewLine, "[Newline]"));
logEvent.AddPropertyIfAbsent(logEventProperty);
}
}
Use following class for Exceptions.
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (logEvent.Exception == null)
return;
var logEventProperty = propertyFactory.CreateProperty("EscapedException", Regex.Replace(logEvent.Exception.ToString(), Environment.NewLine, "[Newline]"));
logEvent.AddPropertyIfAbsent(logEventProperty);
}
Then add these both helper classes into program.cs
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.Enrich.With(new ExceptionEnricher())
.Enrich.With(new MessageEnricher())
.Enrich.FromLogContext()
.CreateLogger();
Update the appsettings output template
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u4} {SourceContext:l} : {EscapedMessage}{NewLine}{EscapedException}{NewLine}"
")) in a Razor view to display lines in a table cell, for example. – GerardF Feb 04 '21 at 15:21