0

I have created a .net framework windows service app, that should use serilog and MS SQL Server to log messages and any potential errors. My issue is that nothing is being logged to MS SQL Server, so I am not sure what the issue is.

As an example (I removed my sensitive code) - I have in the publice Service1() method my initialization for SeriLog, then I want a process to run every 5 minutes, so in the OnStart() I have the timer set-up and I use this code

public Service1()
{
    InitializeComponent();

    var log = new LoggerConfiguration()
        .WriteTo.MSSqlServer(
            connectionString: "data source=ZZZZZZZZ;Initial Catalog=ZZ;Persist Security Info=False;User Id=ZZ; Password=ZZZ;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;",
            sinkOptions: new SinkOptions
            {
                TableName = "SeriLog",
                SchemaName = "dbo",
                AutoCreateSqlTable = false
            })
        .CreateLogger();
}

protected override void OnStart(string[] args)
{
    timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
    timer.Interval = 300000;
    timer.Enabled = true;
}

private void OnElapsedTime(object source, ElapsedEventArgs e)
{
    GetData().GetAwaiter().GetResult();
}
private static async Task GetData()
{
    Log.Information("Started Grabbing Data");
}

Now does anyone see anything that would keep the logging from occuring?

EDIT
I have used this exact code in a console app and it is writing to SQL Server, but when I publish my Windows Service App and have it running as a service, no logs are ever recorded.

C. Augusto Proiete
  • 24,684
  • 2
  • 63
  • 91
  • Does it work in a console app? Can you write anything else to the database. is your connection string right? does this user have the right permissions ? Also though its not part of your problem, if you find your self doing this `.GetAwaiter().GetResult()` you are likely doing something wrong and there is a better way. Anyway this question lacks the suitable debugging and working out needed for a high quality question – TheGeneral Aug 20 '20 at 23:00
  • Yes it works in a console app. I verified that before trying the Windows Service. – jamesMandatory Aug 20 '20 at 23:00
  • Ok well that is a start. You might want to add what you have tried in the question, saves people asking – TheGeneral Aug 20 '20 at 23:02

2 Answers2

4

The first thing you should do when troubleshooting Serilog issues is enable SelfLog, to see if there are any exceptions being thrown. For instance, if the sink is not able to connect to SQL Server, or if there's something wrong with the table, you'll get an error message in the SelfLog.

Serilog.Sinks.MSSqlServer is a "periodic batching sink", so logs are not written immediately to the database. You might want to adjust the configuration options related to batching of messages. Also remember to flush your logs when the service stops otherwise you might lose messages. See Lifecycle of Loggers.

There are a number of steps you can take in order to troubleshoot why your SQL Server sink is not working. The common ones are described in this answer below:

Serilog MSSQL Sink doesn't write logs to database

C. Augusto Proiete
  • 24,684
  • 2
  • 63
  • 91
  • I have not been flushing logs. At what point of the cycle in a Windows Service app should that take place – jamesMandatory Aug 20 '20 at 23:04
  • Usually you would flush the logs just before your service stops (and create a new logger when the service starts). The caveat is that the flush operation must finish before the 30 second window for the service to stop, so you need to make sure your buffer is small enough for the flushing to be finish quickly – C. Augusto Proiete Aug 20 '20 at 23:16
  • Where would that take place? In the Service1.cs file or where? My confusion set's in as should it take place at the end of the events in the ``OnStart`` bc once the timer completes in my head that is where things shutdown – jamesMandatory Aug 20 '20 at 23:16
  • @jamesMandatory The same way that you have an `OnStart` on your service class, you also have an `OnStop`. The timer will be running in a loop forever until you disabled it (whi. [Tutorial: Create a Windows service app](https://learn.microsoft.com/en-us/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer) – C. Augusto Proiete Aug 21 '20 at 13:07
3

You're initializing var log but logging through the static Log class. To enable the static Log class, you need to initialize Log.Logger.

Nicholas Blumhardt
  • 30,271
  • 4
  • 90
  • 101