Implementation example using log4net in ASP. NET MVC
- 2021-11-13 01:13:28
- OfStack
Today, I want to get a log recording function. I have done it before, but I forgot it. Today, I got it again. It took me a few 10 minutes to record it here.
Step 1: Add log4net. dll
Step 2: The configuration example is as follows: I am directly configured under Web. config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<logger name="Student">
<level value="ALL" />
<appender-ref ref="rollingFile" />
</logger>
<appender name="rollingFile" type="log4net.Appender.RollingFileAppender,log4net">
<File value="log/" />
<DatePattern value="yyyy-MM-dd".txt"" />
<StaticLogFileName value="false" />
<maxSizeRollBackups value="-1" />
<RollingStyle value="Date" />
<AppendToFile value="false" />
<MaximumFileSize value="1024MB" />
<layout type="log4net.Layout.PatternLayout,log4net">
<ConversionPattern value="%-38m %-7p %-20d %n" />
</layout>
</appender>
</log4net>
<!-- Not down there! ! ! -->
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
</system.web>
</configuration>
Step 3: Add log4net. Config. XmlConfigurator. Configure () under the Global. asax. cs file; As follows:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
log4net.Config.XmlConfigurator.Configure();
}
}
Step 4: Add the Log helper class and then use it. Note here that the name corresponds to the comments in my code below
public class LogHelper
{
//Student It's your configuration file <logger name="Student"> Adj. name Value of
private static log4net.ILog log = log4net.LogManager.GetLogger("Student");
public static void Debug(object message, Exception e)
{
log.Debug(message, e);
}
public static void Debug(object message)
{
log.Debug(message);
}
public static void Info(object message)
{
log.Info(message);
}
public static void Warn(object message)
{
log.Warn(message);
}
public static void Error(object message)
{
log.Error(message);
}
public static void Error(object message, Exception e)
{
log.Error(message, e);
}
public static void Log(object message)
{
log.Info(message);
}
}
The content of the configuration file is relatively simple and detailed. Look at other more detailed ones.