Home > Back-end >  Serilog only logs messages from Main() into Loggly, in .NET Framework
Serilog only logs messages from Main() into Loggly, in .NET Framework

Time:10-08

I have an app written in .NET Framework 4.7.2 and we're using Serilog to log messages into Loggly.

The issue I have, which I cannot figure out, is that it only logs messages from the Main() method, and does not log messages from other methods down below (or maybe it only logs the very first messages).

I.e. I have a code:

    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration().ReadFrom.AppSettings().Enrich.FromLogContext().WriteTo.Loggly(
            logglyConfig: new LogglyConfiguration
            {
                ApplicationName = ConfigurationManager.AppSettings["Loggly.ApplicationName"],
                CustomerToken = ConfigurationManager.AppSettings["Loggly.CustomerToken"],
                Tags = ConfigurationManager.AppSettings["Loggly.Tags"].Split(',').ToList(),
                EndpointHostName = "xxx.loggly.com",
                EndpointPort = 443,
                IsEnabled = true,
                LogTransport = TransportProtocol.Https,
                ThrowExceptions = false,
                OmitTimestamp = false
            }).CreateLogger();
        Log.Information($"[{nameof(Program)}] Starting...");
        
        Execute();
      }

      public static void Execute()
      {
        Log.Information($"Executing [{nameof(Program)}] ...");

        *... some processing code here ...*
        
        Print();
      }

      public static void Print()
      {
          Log.Information($"Printing Data");

          *... some printing code here ...*
      }

But in the Loggly I only get the first Log ("Starting..."), and none of the others ("Executing" and "Printing").

Any thoughts on what is wrong here or what am I missing?

CodePudding user response:

Sinks like the Loggly sink send messages on a background thread. If your application ends before the background thread was able to send the messages, they are lost and that is likely what's happening in your case...

It's your responsibility to flush the logs before your application ends. See Lifecycle of Loggers.

You do that by calling Log.CloseAndFlush() or by disposing your logger.

public static void Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
        // ...
        .CreateLogger();

    try
    {
        // ...
    }
    finally
    {
        Log.CloseAndFlush(); // <##<##<##<##<##<##
    }
}
  • Related