Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Topshelf.Logging properly

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");                        

            });
        }
    }
like image 913
Friend Avatar asked Sep 25 '22 04:09

Friend


1 Answers

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.

like image 87
stuartd Avatar answered Nov 09 '22 12:11

stuartd