jamesMandatory
jamesMandatory

Reputation: 91

Windows Service Using Serilog No Logs Saved To MS SQL Server

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.

Upvotes: 0

Views: 1713

Answers (2)

Nicholas Blumhardt
Nicholas Blumhardt

Reputation: 31757

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

Upvotes: 3

C. Augusto Proiete
C. Augusto Proiete

Reputation: 27818

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

Upvotes: 4

Related Questions