您现在的位置是:首页 >技术教程 >log4net在Asp.net MVC4中的使用网站首页技术教程
log4net在Asp.net MVC4中的使用
简介log4net在Asp.net MVC4中的使用
1、安装log4net插件
新建Asp.net MVC4项目,并在Nuget控制台输入命令,或者直接搜索log4net在线安装,安装log4net
>Install-Package log4net -Version 2.0.15
2、配置web.config文件
<?xml version="1.0" encoding="utf-8"?>
<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
https://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<log4net>
<root>
<level value="ALL"></level>
<appender-ref ref="SysAppender"></appender-ref>
</root>
<logger name="WebLogger">
<!--日志输出级别限制,只有大于或等于DEBUG级别才记录日志-->
<level value="DEBUG"></level>
</logger>
<!--以滚动日志方式记录日志-->
<appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net">
<!--文件存放路径,在项目根目录App_Data下-->
<param name="File" value="App_Data/"></param>
<!--日志是否追加到文件-->
<param name="AppendToFile" value="true"></param>
<!--滚动日志文件按照日期风格生成-->
<param name="RollingStyle" value="Date"></param>
<!--日志文件的命名规则-->
<param name="DatePattern" value=""Logs_"yyyyMMdd".txt""></param>
<!--日志名称是否静态-->
<param name="StaticLogFileName" value="false"></param>
<!--日志内容的格式和布局-->
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"></param>
<param name="Header" value="-------------------------header---------------------------"></param>
<param name="Footer" value="-------------------------footer---------------------------"></param>
</layout>
</appender>
<!--按照控制台输出日志-->
<appender name="ConsoleApp" type="log4net.Appender.ConsoleAppender,log4net">
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"></param>
</layout>
</appender>
</log4net>
<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.6.1" />
<httpRuntime targetFramework="4.6.1" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" />
<bindingRedirect oldVersion="0.0.0.0-4.0.2.1" newVersion="4.0.2.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.webServer>
<modules>
<remove name="TelemetryCorrelationHttpModule" />
<add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE="Web" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
日志级别分类(从高到低):OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL
3、初始化log4net
在Global.asax中初始化log4net配置
log4net.Config.XmlConfigurator.Configure();
4、定义异常拦截器
自定义异常拦截器,出现控制器action方法调用出现异常时,将异常信息统一加入到全局队列中,避免日志写入文件并发冲突。
public class MyErrorAttribute:HandleErrorAttribute
{
public static Queue<Exception> ExceptionQueue = new Queue<Exception>();
public override void OnException(ExceptionContext filterContext)
{
ExceptionQueue.Enqueue(filterContext.Exception);
base.OnException(filterContext);
}
}
将全局默认异常处理器替换为自己定义的。
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//filters.Add(new HandleErrorAttribute());//默认异常处理器
filters.Add(new MyErrorAttribute());//自定义异常处理器
}
}
5、后台线程轮询异常队列,将日志写入到文件
启动类Global.asax.cs文件中定义后台线程,处理异常队列中日志的输出
//启动后台线程,周期性轮询异常队列,将异常输出到文件
ThreadPool.QueueUserWorkItem(o => {
while(true)
{
if(MyErrorAttribute.ExceptionQueue.Count>0)
{
Exception ex = MyErrorAttribute.ExceptionQueue.Dequeue();
if(ex!=null)
{
ILog log = LogManager.GetLogger("testError");
log.Error(ex.ToString());
}
else
{
Thread.Sleep(50);
}
}
else
{
Thread.Sleep(50);
}
}
});
6、控制器中定义异常测试方法
public ActionResult TestLog()
{
int result = 0;
int x = 1, y = 0;
result = x / y;
return View();
}
7、启动程序测试action方法
查看项目根目录App_Data,生成了日志文件Logs_20230520.txt
查看日志内容
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。