Guy Cothal
Guy Cothal

Reputation: 1348

Attach console to .Net Windows Service

I currently have several .Net windows services running on my server. Is there a way to attach a console app to the service to get all of the ILogger data? I have had issues where the service runs perfectly as a console app/worker service but as soon as I run it as a windows service, it just sits there and does nothing.

I did find an article about attaching the VS debugger to the process, but this will not work with our network security.

I am open to any other suggestions as well.

Upvotes: 1

Views: 635

Answers (1)

user15716642
user15716642

Reputation: 550

The technical answer is no, but as @Fildor mentioned, you would set up a log sink of some sort. The file logger is just an example, but you can also have the logs send emails, post to some cloud logging service such as splunk or cloudwatch, etc.

One issue you may run into is that you need to capture an error prior to ILogger being available and properly configured for you. Here is a guide I followed for capturing startup errors using NLog: https://alistairevans.co.uk/2019/10/04/asp-net-core-3-0-logging-in-the-startup-class-with-nlog/

Startup classes are no longer necessary in the latest .NET version, so I modified their example to be code you would have in Program.cs:

// NLog: setup the nlog config first
NLogBuilder.ConfigureNLog("nlog.config");

try
{
    var host = Host.CreateDefaultBuilder(args)
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.SetMinimumLevel(LogLevel.Trace);
        })
        // Use NLog to provide ILogger instances.
        .UseNLog()
        .Build();

    host.Run();
}
catch (Exception ex)
{
    var logger = nlogLoggerProvider.CreateLogger(typeof(Program).FullName);
}

}

Here's the list of available log sinks you can configure in that nlog configuration file: https://nlog-project.org/config/

This same thing can be accomplished with other log providers you may already be using such as Serilog, Log4Net, etc.

Upvotes: 1

Related Questions