dasMulli/dotnet-win32-service

NLog not writing logs when running as a service

Closed this issue · 3 comments

Thanks for this library. It's let me create a simple Windows Service on .NET Core 1.1 without needing all of the AspNetCore libs.

I realize this issue may not be related to your library, but I figured I'd ask in case you have any ideas.

I am using the .NET Core ILogger along with NLog. When I run my service as a console app, the logging works correctly, both to console and to file. But when I run it as a service, I get no logging, and nothing in the internal NLog log to explain why. The service itself still runs.

Here's the code from Main():

        var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
        loggerFactory.AddNLog();

        var myServiceClass = serviceProvider.GetService<MyServiceClass>();

        if (Debugger.IsAttached || args.Contains("--console"))
        {
            // Logging works here
            threadManager.Start(new string[0], () => { });

            while (Console.ReadKey().KeyChar != 'q') { }

            threadManager.Stop();
        }
        else
        {
            // No logging when I run it this way
            var serviceHost = new Win32ServiceHost(threadManager);
            serviceHost.Run();
        }

hello!

My first guess without trying it out is that NLog needs an NLog.config. Windows services are started with your windows installation's %WINDIR%\system32 folder as working directory, so NLog might not find the config file automatically. Especially when running "portable" applications, where the running executable is actually a dotnet.exe in your program files directory.
Could you try explicitly specifying the NLog config file programmatically? According to the docs, you could do sth like:

using System.IO;
using System.Reflection;var assemblyPath = typeof(Program).GetTypeInfo().Assembly.Location;
var appDirectory = Path.GetDirectoryName(assemblyPath);
var nlogConfigFile = Path.Combine(appDirectory, "NLog.config");
LogManager.Configuration = new XmlLoggingConfiguration(nlogConfigFile);

Let me know if this helps or else I'll need to create a test app.

That did it! Thanks! I didn't realize that a service starts in system32

Glad I could help!