Search code examples
c#nlog

Can you force a log entry when calling BeginScope()?


When logging via

using (_logger.BeginScope("SomeScope"))
{
...
}

is it possible to force _logger.BeginScope() to make a log entry on its own without the use of an explicit log command like _logger.LogInformation() later on inside the using statement?

I have also already seen this post and was successful implementing it. But I was wondering if it was also possible to the log output without the use of an extension class.


Solution

  • In the typical usage of logging frameworks in C# (like Serilog, NLog, or log4net), calling BeginScope() itself doesn't generate a log entry. Instead, it's used to create a logical scope for the logging context, allowing you to attach additional information to log entries within that scope.

    If you want to force a log entry when entering a scope, you'd need to manually emit a log entry within the scope. Refer to the example here using Serilog:

    using Serilog;
    using Serilog.Context;
    
    class Program
    {
        static void Main()
        {
            Log.Logger = new LoggerConfiguration()
                .WriteTo.Console()
                .CreateLogger();
    
            using (LogContext.PushProperty("ScopeInfo", "Entering the scope"))
            {
                Log.Information("Log entry within the scope.");
            }
    
            Log.Information("Log entry outside the scope.");
    
            Log.CloseAndFlush();
        }
    }