Using Topshelf to develop Windows services and record logs

Keywords: ASP.NET Windows

To develop windows service, in addition to creating a new service project in vs (there have been written specific development methods before, you can click See ), you can also use Topshelf.

However, using topshelf requires. Netframework version 4.5.2, which is not successful on vs2013. I use vs2017 here.

The following are the specific steps:

1, Reference topshelf and use

1. New console program in vs

2. Use NuGet to search for topshelf in references and install

3. Program code

using log4net;
using System;
using System.IO;
using System.Reflection;
using System.Timers;
using Topshelf;

namespace TopshelfTest
{
    public class TestWriteLog
    {
        readonly Timer _timer;
        ILog _log = LogManager.GetLogger(typeof(TestWriteLog));
        public TestWriteLog()
        {
            _timer = new Timer(1000)
            {
                AutoReset = true,
                Enabled = true
            };
            int i = 0;
            _timer.Elapsed += delegate (object sender, System.Timers.ElapsedEventArgs e)
            {
                i++;
                _log.Info("test" + i.ToString());

            };
        }

        public void Start()
        {
            _log.Info("Service is Started");
            _timer.Start();
        }
        public void Stop()
        {
            _log.Info("Service is Stopped");
            _timer.Stop();
        }


        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            
            HostFactory.Run(c =>
            {
                c.Service<TestWriteLog>((x) =>
                {
                    x.ConstructUsing(name => new TestWriteLog());
                    x.WhenStarted((t) => t.Start());
                    x.WhenStopped((t) => t.Stop());
                });
                c.RunAsLocalSystem();
                //Service description
                c.SetDescription("TestServices Test service description");
                //Service display name
                c.SetDisplayName("TestServices Test service display name");
                //Real name of the service
                c.SetServiceName("TestServices");
            });
        }
    }
}

 

4. log4net reference and configuration method

4.1 use the above method to reference log4net.dll

4.2 make the following configuration in app.config

 <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

  <log4net>
    <!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
    <!-- Set root logger level to ERROR and its appenders -->
    <root>
      <level value="ALL" />
      <appender-ref ref="SysAppender" />
    </root>
    <!-- Print only messages of level DEBUG or above in the packages -->
    <logger name="WebLogger">
      <level value="log" />
    </logger>
    <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net">
      <!--<param name="File" value="App_Data/" />-->
      <File value="Logs\log" />
      <!--Log file location and file name-->
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <!--<param name="DatePattern" value="&quot;Logs_&quot;yyyyMMdd&quot;.txt&quot;" />-->
      <param name="DatePattern" value="yyyyMMdd&quot;.txt&quot;" />
      <!--Add something after the file name, such as log Name change log20180808-->
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
      </layout>
    </appender>
    <appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net">
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
      </layout>
    </appender>
  </log4net>

4.3 add the following configuration in AssemblyInfo.cs of properties

 

[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]

5. Generate project

After the project is generated, you can copy the content in bin\debug to the location where the service is placed separately,

6. Install, uninstall services

Use the administrator to run cmd and cd to your service file location. I will install the service directly in debug here.

Service.exe install ----- install Service

You can see the installed Service in the service

 

Service.exe uninstall ----- uninstall the service

 

7. Operation results

Start service after service installation

Posted by mnewhart on Tue, 24 Dec 2019 12:33:59 -0800