Avoid logging Context info if empty & Template of console

824 views
Skip to first unread message

paolo ponzano

unread,
Apr 12, 2016, 6:21:14 AM4/12/16
to Serilog
Hello,
I've used the contextinfo to log some additional data as NDG and datetime during a loppo procedure as

  Parallel.ForEach(items, new ParallelOptions
                {
                    MaxDegreeOfParallelism = ServiceStackHost.Instance.AppSettings.Get<int>("threads", 5)
                }, ndg =>
                {
                    using (LogContext.PushProperty("NDG", ndg.NDG))
                    {
                        using (LogContext.PushProperty("Data", ndg.Date))
                        {
                            Log.Information("Recuperando il report");

                           //something splendid or weird...it depends
                        }
                    }
                });
            };


and it produces this output

12:11:15 [ - ] [Information] Mapping recuperato
12:11:15 [000002672 - 03/29/2016 00:00:00] [Information] Recuperando il report

My template is defined as

<add key="serilog:write-to:RollingFile.outputTemplate" value="{Timestamp:HH:mm:ss} [ndg:{NDG} - {Data:dd-MM-yyyy}] [{Level}]  {Message}{NewLine}{Exception}"/>

How can I avoid to write [ - ] when those context info are no avaiable? is there a simple way?

The second part of the question is regarding the log console, why this template is not applied?

<add key="serilog:write-to:Console" value="{Timestamp:HH:mm:ss} [ndg :{NDG} - {Data:dd-MM-yyyy}] [{Level}]  {Message}{NewLine}{Exception}" />

Thanks
Paolo

nblum...@nblumhardt.com

unread,
Apr 12, 2016, 6:45:59 PM4/12/16
to Serilog
Hi Paolo,

No, there's no built-in conditional formatting to do what you want here. The recommended "hack" is to use a custom ITextFormatter (you can pass this into the sink) that delegates to two MessageTemplateTextFormatters each using different templates. The custom formatter can inspect a log event for the presence of the NDG property and choose which template formatter to use based on that.

Regarding the second example, the "key" attribute is missing the ".outputTemplate" part, try:

<add key="serilog:write-to:Console.outputTemplate" value="{Timestamp:HH:mm:ss} [ndg :{NDG} - {Data:dd-MM-yyyy}] [{Level}]  {Message}{NewLine}{Exception}" />

Best regards,
Nick
Reply all
Reply to author
Forward
0 new messages