One, create a new console application
Ii. using NuGet to refer to Topshelf and log4net plugins
Third, log4net configuration file add
Adding Log4net.config files and Loghelper class libraries to the root directory
Log4net.config content is as follows:
<?xml version="1.0"encoding="Utf-8"?><configuration> <configSections> <section name="log4net"Type="log4net. Config.log4netconfigurationsectionhandler, Log4net"/> </configSections> <log4net> <!--information log configuration--<appender name="Infologfileappender"Type="log4net. Appender.rollingfileappender"> <param name="File"Type=""Value="log\\info\\"/> <param name="Appendtofile"Value="true"/> <param name="maxsizerollbackups"Value=" -"/> <param name="Rollingstyle"Value="Date"/> <param name="Datepattern"Value="yyyy-mm-dd '. Log '"/> <param name="Staticlogfilename"Value="false"/> <layout type="log4net. Layout.patternlayout,log4net"> <param name="Conversionpattern"Value="%d [%5p]%c:%m%n"/> </layout> <filter type="log4net. Filter.levelrangefilter,log4net"> <levelmin value="INFO"/> <levelmax value="INFO"/> </filter> </appender> <!--error log configuration-<appender name="Errorlogfileappender"Type="log4net. Appender.rollingfileappender"> <param name="File"Type=""Value="log\\error\\"/> <param name="Appendtofile"Value="true"/> <param name="maxsizerollbackups"Value=" -"/> <param name="Rollingstyle"Value="Date"/> <param name="Datepattern"Value="yyyy-mm-dd '. Log '"/> <param name="Staticlogfilename"Value="false"/> <layout type="log4net. Layout.patternlayout,log4net"> <param name="Conversionpattern"Value="%d [%5p]%c:%m%n"/> </layout> <filter type="log4net. Filter.levelrangefilter,log4net"> <levelmin value="ERROR"/> <levelmax value="ERROR"/> </filter> </appender> <root> <level value=" All"/> <appender-ref ref="Errorlogfileappender"/> <appender-ref ref="Infologfileappender"/> </root> <logger name=" All"> <level value=" All"/> <appender-ref ref="Errorlogfileappender"></appender-ref> <appender-ref ref="Infologfileappender"></appender-ref> </logger> </log4net></configuration>
Loghelper Class Library:
usinglog4net;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Reflection;usingSystem.Text;usingSystem.Threading.Tasks;namespacewindowsservice1{ Public classLoghelper { Public StaticILog getlog<t>(T t) {ILog _log= Logmanager.getlogger (""); if(t! =NULL) {_log=Logmanager.getlogger (T.gettype ()); } return_log; } }}
Iv. writing a service function class "Print a log every 3 seconds"
usinglog4net;usingSystem;usingSystem.IO;usingSystem.Reflection;usingsystem.timers;namespacewindowsservice1{ Public classTestwritedate {ReadOnlyTimer _timer; Publictestwritedate () {_timer=NewTimer ( the) {AutoReset=true, Enabled=true }; _timer. Elapsed+=Delegate(Objectsender, System.Timers.ElapsedEventArgs e) {Loghelper.getlog ( This). Info (string. Format ("DATE: {0}", DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss"))); Loghelper.getlog ( This). Error ("Test Error!!! ",NewException ("DFSAFDSAFDDSAFDSA")); Try { inti =0; intj =Ten/i; } Catch(Exception ex) {Loghelper.getlog ( This. GetType ()). Error (ex. Message, ex); } }; } Public voidStart () {Loghelper.getlog ( This). Info ("Start Execution"); } Public voidStop () {Loghelper.getlog ( This). Info (string. Format ("End Execution") + Environment.NewLine +Environment.NewLine); _timer. AutoReset=false; _timer. Enabled=false; } }}
V. Integration with Topshelf
Program.cs's Code:
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Reflection;usingsystem.serviceprocess;usingSystem.Text;usingSystem.Threading.Tasks;usingtopshelf;namespacewindowsservice1{Static classProgram {/// <summary> ///The main entry point for the application. /// </summary> Static voidMain () {stringAssemblyfilepath =assembly.getexecutingassembly (). Location; stringAssemblydirpath =Path.getdirectoryname (Assemblyfilepath); stringConfigFilePath = Assemblydirpath +"\\log4net.config"; Log4net. Config.XmlConfigurator.Configure (NewFileInfo (ConfigFilePath)); Hostfactory.run (c={C.service<TestWriteDate> ((x) = ={x.constructusing (name=Newtestwritedate ()); X.whenstarted ((t)=T.start ()); X.whenstopped ((t)=t.stop ()); }); C.runaslocalsystem (); //Service DescriptionC.setdescription ("test_services"); //Service Display NameC.setdisplayname ("test_services"); //the real name of the service }); } }}
Vi. installation and uninstallation of services
1, installation Install.bat
/d%~dp0WindowsService1.exe installnet start Test_servicespause
2, uninstall Uninstall.bat
/d%~dp0WindowsService1.exe uninstallpause
Vii. Source Code
Click to download
Use Topshelf to create a Windows service that uses log4net logging in a service