How to use Topshelf.Logging properly
Asked Answered
G

1

6

Any clue how to use Topshelf.Logging properly?

Do I have to pass NLogLogWriter to the constructor of the service class?

And how to enable output to console as well?

class Program
    {
        #region Properties
        Topshelf.Logging.NLogLogWriter logger;
        static string mainLoggerName = "MainLogger";
        #endregion

        static void Main(string[] args)
        {
            var  nlogLogger = LogManager.GetCurrentClassLogger();
            Topshelf.Logging.NLogLogWriter logger = new Topshelf.Logging.NLogLogWriter(nlogLogger, mainLoggerName);


            HostFactory.Run(x =>                                 
            {
                x.Service<ExSPCAgentService>(s =>                         
                {
                    s.ConstructUsing(name => new MyAgentService());      

                    // s.WhenStarted(tc => tc.Start());               
                    s.WhenStarted(tc =>
                    {
                        // Add more config options if you need
                        tc.Start();
                    });
                    s.WhenStopped(tc => tc.Stop());                
                });
                x.RunAsLocalSystem();                             
                x.UseNLog();
                x.SetDescription("MyAgentService");         
                x.SetDisplayName("MyAgentService");                        
                x.SetServiceName("MyAgentService");                        

            });
        }
    }
Guanabana answered 3/3, 2016 at 13:8 Comment(0)
C
6

To specify your logger, use the overload of UseNLog that lets you specify a LogFactory.

For logging to console you would enable a console target.

Edit: docs

NLog Integration

To enable logging via NLog, the Topshelf.NLog NuGet package is available. Once added to your project, configure Topshelf to use NLog via the configuration:

HostFactory.New(x =>
{
    x.UseNLog();
});

This will change the HostLogger to use NLog. An existing LogFactory can be passed as well, using an overload of the same method.

Capitalization answered 3/3, 2016 at 13:24 Comment(3)
Thank you! The second part about the console target was useful. Would u mind to provide an example about LogFactory, please.Guanabana
When using x.UseNLog(existingLogFactory), it isn't possible to reach this factory in another class. I tried to use LogManager.GetCurrentClassLogger(), but the LogManagers configuration is null. What must be done to can use the exist logFactory in other classes and modules? Btw, I use Lamar as IoC. Thanks :)Crustacean
Well, you could make the log factory a static class member?Capitalization

© 2022 - 2024 — McMap. All rights reserved.