4

I have serilog on my .net core app basic config as follows:-

Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(Configuration)
        .Enrich.FromLogContext()
        .WriteTo.File(@"./logs/log-.log", rollingInterval: RollingInterval.Day, outputTemplate: LOG_TEMPLATE)
        .WriteTo.Console(outputTemplate: LOG_TEMPLATE, theme: AnsiConsoleTheme.Literate)
        .WriteTo.SomeOtherLog()
        .CreateLogger();

Lets now say I wish to write to SomeOtherLog based on a condition. How would one go about that?

Something like

if(conditon)
.WriteTo.SomeOtherLog()
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
AliK
  • 962
  • 2
  • 10
  • 31

2 Answers2

9

As of Serilog 2.9.0 you can now use .WriteTo.Conditional and specify the condition that defines if the sink will be written to or not.

Log.Information("Hello");
Log.CloseAndFlush();

var configuration = new LoggerConfiguration()
    .ReadFrom.Configuration(Configuration)
    .Enrich.FromLogContext()
    .WriteTo.File(@"./logs/log-.log", rollingInterval: RollingInterval.Day,
        outputTemplate: LOG_TEMPLATE)
    .WriteTo.Console(outputTemplate: LOG_TEMPLATE, theme: AnsiConsoleTheme.Literate)
    .WriteTo.Conditional(evt => condition, wt => wt.SomeOtherLog());

Log.Logger = configuration.CreateLogger();
// ...
C. Augusto Proiete
  • 24,684
  • 2
  • 63
  • 91
  • 1
    Augusto .. is `evt => condition` evaluated only at 'creation'?.. or if the condition changes at runtime, that '.WriteTo.' will be toggled on/off? I was searching for documentation to `.WriteTo.Conditional(...)` but could not find any; could you amend the answer above to show a working `evt => condition, wt => wt.SomeOtherLog()` – George 2.0 Hope Feb 22 '22 at 20:53
  • 2
    @George2.0Hope I had the same question about condition changing at runtime. I tested changing condition at runtime and '.WriteTo' is toggled. – Brian Dec 21 '22 at 19:41
4
var configuration = new LoggerConfiguration()
        .ReadFrom.Configuration(Configuration)
        .Enrich.FromLogContext()
        .WriteTo.File(@"./logs/log-.log", rollingInterval: RollingInterval.Day,
                      outputTemplate: LOG_TEMPLATE)
        .WriteTo.Console(outputTemplate: LOG_TEMPLATE, theme: AnsiConsoleTheme.Literate);

if (condition)
{
    configuration.WriteTo.SomeOtherLog();
}

Log.Logger = configuration.CreateLogger();
Nicholas Blumhardt
  • 30,271
  • 4
  • 90
  • 101
  • Thanks I can't believe I missed that. – AliK Sep 09 '19 at 06:12
  • Great, question what could be this condition? Because I can see that the condition IF is inside the setup, what about if inside my c# controller I need to do that condition to choose what SINK to use? Question, my Serilog configuration is in my appsettings.json, can I still do that conditional and how? Appreciate it – VAAA Aug 25 '22 at 16:30