I have read n log4net tutorials. Although many of them are about using log4net in web projects, none of them has been successfully tested.
Dizzy! After studying for half an hour, I finally got it done.
1. Modify assemblyinfo. CS
[Assembly: log4net. config. xmlconfigurator (configfile = "log4net. config", watch = true)]
2. modify web. config
<Configuration>
<Configsections>
<Section name = "log4net" type = "log4net. config. log4netconfigurationsectionhandler, log4net"/>
</Configsections>
<System. Web>
... Automatically generated Configuration
</System. Web>
</Configuration>
3. Create a logger. CS class
Public class Logger
{
Private Static log4net. ilog log = NULL;
Private Static object lockhelper = new object ();
Public static log4net. ilog log
{
Get
{
If (log = NULL)
{
Lock (lockhelper)
{
If (log = NULL)
Log = log4net. logmanager. getlogger ("logger ");
}
}
Return log;
}
}
}
4. Create log4net. config
<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Log4net DEBUG = "false">
<Appender name = "logfileappender" type = "log4net. appender. fileappender">
<File value = "log.txt"/>
<Appendtofile value = "true"/>
<Layout type = "log4net. layout. patternlayout">
<Conversionpattern value = "% date [% thread] %-5 level % logger [% NDC]-% message % newline"/>
</Layout>
</Appender>
<Root>
<Level value = "all"/>
<Appender-ref = "logfileappender"/>
</Root>
</Log4net>
</Configuration>
5. Call Method
Logger. log. debug ("hello ");
6. Make sure that the folder where the Web is located has the write permission.
7. OK
If you have problems using log4net, set it in log4net. config.
<Log4net DEBUG = "true">
In this way, you can see the error information.
At first, I didn't set the write permission for the file, so I failed to use it. Then I opened debug and saw the error message. Therefore, when you have problems using log4net, you must enable debug to check the error message, which is very useful.