How to correctly use log4net in Windows Services

Source: Internet
Author: User
Tags log4net
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 >
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.