NLog allows me to use SplitGroup to log my messages to several targets. I\'d like to use this feature to log each message to a common, user-specific and date-specific lo
I'm not sure, but I think that you are probably stuck with the duplication. You want 4 different layouts to be used on the same file and you want 3 different files. One target requires one Layout. So, if you only wanted to log to 1 file, you would still have to define 4 Targets, each pointing to the same file and each with its own Layout. I don't think that NLog has a more convenient way to associate multiple Layouts with a Target and then choosing one Layout based on the content of the logging message.
Depending on exactly what you want to achieve with your formats, you might be able to reduce the duplication somewhat by writing a custom LayoutRenderer. In your example, you show that the Debug layout has "..." in it, Info has [i], Warn has [!], and Error has Warn + exception. You could write a LayoutRenderer that adds the special marker, depending on what the level of the message is. That way, you would roll Debug, Info, and Warn all into one Layout and Error would retain its own Layout.
For example:
Something like this for a custom LayoutRenderer (based on NLog 1.0 refresh, not 2.0):
[LayoutRenderer("LevelMarkerLayoutRenderer")]
class LevelMarkerLayoutRenderer : LayoutRenderer
{
int estimatedSize = 3;
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
string marker;
switch (logEvent.Level)
{
case Debug:
marker = "...";
break;
case Info:
marker = "[i]";
break;
case Warn:
marker = "[!]";
break;
case Error:
marker = "[!]";
break;
case Fatal:
marker = "[!]";
break;
default:
marker = "?";
}
builder.Append(marker);
}
protected override int GetEstimatedBufferSize(LogEventInfo logEvent)
{
return estimatedSize;
}
}
Now you could configure two Layouts: "normal", and "error".
Something like:
You could probably even create a custom LayoutRenderer to handle exceptions. If no exception, don't output anything. If exception, concatentate newline, padding, and the exception string.
If you had a "conditional" exception layout renderer, then you could have just one layout that might look like this:
Most of the time, ConditionalExceptionLayoutRenderer would yield null because there would not be an exception.
Hope this helps.