如何正确使用Topshelf.Logging

How to use Topshelf.Logging properly

知道如何正确使用 Topshelf.Logging 吗?

是否必须将 NLogLogWriter 传递给服务 class 的构造函数?

以及如何启用输出到控制台?

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

            });
        }
    }

要指定您的记录器,请使用 overload of UseNLog that lets you specify a LogFactory

要将日志记录到控制台,您需要启用 console target

编辑: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.