Search code examples
c#.net.net-6.0background-service

WorkerService unable to log messages on deployment machine


I am building a WorkerService in C# that runs as a Windows Service. When testing I am able to see log messages fine as there is a console window displaying the information or error messages. When I deploy there is no console window as this is a service with no GUI to speak of. I would still like to log informational messages and errors though. Right now I can see information in the Event Viewer showing the service starting and stopping and displaying any errors but I would like to potentially have a log file I can add more detailed information to. Here is what my BackgroundWorker looks like.

public class WindowsBackgroundService : BackgroundService
{
    private readonly ILogger<WindowsBackgroundService> logger;

    public WindowsBackgroundService(ILogger<WindowsBackgroundService> logger)
    {
        this.logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        //Logic would go here.
        logger.LogInformation($"New User {newCustomer.Firstname} {newCustomer.Lastname} Added");
    }
    await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
}

Here is my Program.cs in case anyone is curious or it has anything to do with it.

var host = Host.CreateDefaultBuilder(args)
.UseWindowsService(options =>
{
    options.ServiceName = "Customer Broker Service";
})
.ConfigureServices(services =>
{
    services.AddHostedService<WindowsBackgroundService>();
})
.Build();

await host.RunAsync();

When I try and use the logger while the service is running on the deployment machine it crashes the service because there is no console window to display the log. I am thinking I am missing something real simple here.


Solution

  • You can try using Serilog, just include Serilog nuget package in your project, and in your code :

    var host = Host.CreateDefaultBuilder(args)
    .UseSerilog()
    .UseWindowsService(options =>
    {
        options.ServiceName = "Customer Broker Service";
    })
    .ConfigureServices((hostContext, services) =>
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.RollingFile(@"C:\logs\log.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();
        services.AddHostedService<WindowsBackgroundService>();
    })
    .Build();
    
    await host.RunAsync();
    

    You need to get sure the path "C:\logs" exists, or change the path accordingly in the code above. Your worker code should not need any change.