I wrote a Windows service a few days ago. Program Log4net always fails.
The configuration of log4net is the same in APP. config or in an independent config file.
Today, we finally found that the configuration file was not correctly located in the service.
After trying, we found that the key lies in the following: Code To obtain the path of the config file. In this way, the log can be output correctly:
Public Class Service1: servicebase
{
// Main Process entry point
Private Static Void Main ()
{
String Assemblyfilepath = Assembly. getexecutingassembly (). location;
String Assemblydirpath = Path. getdirectoryname (assemblyfilepath );
String Configfilepath = Assemblydirpath + " \ Log4net. config " ;
Domconfigurator. configureandwatch ( New Fileinfo (configfilepath ));
Servicebase [] servicestorun;
Servicestorun = New Servicebase [] {NewService1 ()} ;
Servicebase. Run (servicestorun );
}
// Others
}
I don't need to write much about the others, with my log4net. config:
<? XML version = "1.0" encoding = "UTF-8" ?>
< Log4net >
< Appender Name = "Rollinglogfileappender" Type = "Log4net. appender. rollingfileappender" >
< File Value = "Logs/log.txt" />
< Appendtofile Value = "True" />
< Rollingstyle Value = "Size" />
< Maxsizerollbackups Value = "10" />
< Maximumfilesize Value = "100kb" />
< Staticlogfilename Value = "True" />
< Layout Type = "Log4net. layout. patternlayout" >
< Conversionpattern Value = "% D [% T] %-5 p % C [% x]-% m % N" />
</ Layout >
</ Appender >
< Root >
< Level Value = "All" />
< Appender-ref Ref = "Rollinglogfileappender" />
</ Root >
</ Log4net >