Log4Net使用
log4net是.Net下一个非常优秀的开源日志记录组件,至于有何优势或者说需要更深层的挖掘,可能就需要您更多的摸索了。
结果先上
INFO 2019-07-13 15:02:48,369 [9 ] Index - 正常日志
INFO 2019-07-13 15:02:48,398 [9 ] Index - 异常日志:System.FormatException: 输入字符串的格式不正确。
在 System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
在 System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
在 System.Int32.Parse(String s)
在 WindowsFormsApplication1.Form1.button1_Click(Object sender, EventArgs e) 位置 C:\Users\Administrator\Desktop\test\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:行号 26
winfrom程序实现
先说一下思路和流程
- 新建winfrom程序 ,我就命名WindowsFormsApplication1好了
- 程序NuGet引入Log4Net类库,两种引入方法:第一种,程序包管理控制台输入Install-Package Log4Net;第二种在管理解决方案NuGet程序包中次搜索Log4Net然后安装。
- App.config文件配置Log4Net
- Properties下AssemblyInfo文件配置Log4Net
- 新建一个Helper文件夹,里面新建一个Log4NetHelper类,
- 调用Log4NetHelper类(第3点新建的),完成。
第1和第2点就不说了直接第3点,开始实现----------啥都别说了,代码走起
App.config文件配置Log4Net <!--log4net配置 start--> ... <!--log4net配置 end-->
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<!--log4net配置 start-->
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<root>
<appender-ref ref="CollectFileAppender" />
<level value="DEBUG" />
</root>
<!--logger 名Index-->
<logger name="Index">
<level value="INFO" />
<appender-ref ref="LoginAppender" />
</logger>
<appender name="LoginAppender" type="log4net.Appender.RollingFileAppender,log4net">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<!--日志路径-->
<file value="Logs/Index/" />
<datePattern value="yyyyMMdd-HH'.txt'" />
<appendToFile value="true" />
<staticLogFileName value="false" />
<rollingStyle value="Composite" />
<maximumFileSize value="10MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level %date [%-5.5thread] %-40.40logger - %message%newline" />
</layout>
</appender>
</log4net>
<!--log4net配置 end-->
</configuration>
Properties下AssemblyInfo文件配置Log4Net,在文件后面加一条便可。
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("WindowsFormsApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WindowsFormsApplication1")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("fcde1dc6-eff9-42d8-abc3-91c6e9d506ba")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
新建一个类Log4NetHelper
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication1.Helper
{
public class Log4NetHelper
{
public static log4net.ILog logIndex = log4net.LogManager.GetLogger("Index");
}
}
拉一个button控件,然后点击触发后方法如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApplication1.Helper;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Log4NetHelper.logIndex.Info("正常日志");
try
{
int readValue = int.Parse("haha");
}
catch (Exception ex)
{
Log4NetHelper.logIndex.Info("异常日志");
}
}
}
}
成功运行程序后,在程序的 bin\Debug\Logs\Index 路径就可以看到一个日志文件了,当然了,这个路径是第3步App.config文件配置的时候定义的。
INFO 2019-07-13 15:02:48,369 [9 ] Index - 正常日志
INFO 2019-07-13 15:02:48,398 [9 ] Index - 异常日志:System.FormatException: 输入字符串的格式不正确。
在 System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
在 System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
在 System.Int32.Parse(String s)
在 WindowsFormsApplication1.Form1.button1_Click(Object sender, EventArgs e) 位置 C:\Users\Administrator\Desktop\test\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:行号 26
--------------------------------------------------------------------web MVC程序实现---------------------------------------------------------------------------------
web MVC程序实现
其实和上面winfrom说的基本一样,思路和流程如下
- 新建web MVC程序 ,我就命名WebApplication1好了
- 程序NuGet引入Log4Net类库,两种引入方法:第一种,程序包管理控制台输入Install-Package Log4Net;第二种在管理解决方案NuGet程序包中次搜索Log4Net然后安装。
- Web.config文件配置Log4Net
- Properties下AssemblyInfo文件配置Log4Net
- 新建一个Helper文件夹,里面新建一个Log4NetHelper类,
- Global.asax文件配置Log4Net
- 调用Log4NetHelper类(第3点新建的),完成。
第1和第2点就不说了直接第3点,开始实现----------啥都别说了,代码走起
Web.config文件配置Log4Net. 一: 在<configSections>标签中加入一条 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> 二:在<connectionStrings>标签的前面加入Log4Net.配置 <!--log4net配置 start--> ... <!--log4net配置 end-->
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!--加一个log4net section-->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<!--log4net配置 start-->
<log4net>
<root>
<appender-ref ref="CollectFileAppender" />
<level value="DEBUG" />
</root>
<!--logger 名Index-->
<logger name="Index">
<level value="INFO" />
<appender-ref ref="LoginAppender" />
</logger>
<appender name="LoginAppender" type="log4net.Appender.RollingFileAppender,log4net">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<!--日志路径-->
<file value="Logs/Index/" />
<datePattern value="yyyyMMdd-HH'.txt'" />
<appendToFile value="true" />
<staticLogFileName value="false" />
<rollingStyle value="Composite" />
<maximumFileSize value="10MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level %date [%-5.5thread] %-40.40logger - %message%newline" />
</layout>
</appender>
</log4net>
<!--log4net配置 end-->
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-WebApplication1-20190713030746.mdf;Initial Catalog=aspnet-WebApplication1-20190713030746;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<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>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.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.5.2.14234" newVersion="1.5.2.14234" />
</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.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.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>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
Properties下AssemblyInfo文件配置Log4Net,在文件后面加一条便可。
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息是通过以下项进行控制的
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("WebApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebApplication1")]
[assembly: AssemblyCopyright("版权所有(C) 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 将使此程序集中的类型
// 对 COM 组件不可见。如果需要
// 从 COM 访问此程序集中的某个类型,请针对该类型将 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于 typelib 的 ID
[assembly: Guid("bc4883a3-b666-4505-847c-ed223444463c")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订版本
//
// 你可以指定所有值,也可以让修订版本和内部版本号采用默认值,
// 方法是按如下所示使用 "*":
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
新建Log4NetHelper类
public class Log4NetHelper
{
public static log4net.ILog logIndex = log4net.LogManager.GetLogger("Index");
public static void LoadConfig(string configFilePath)
{
if (string.IsNullOrEmpty(configFilePath) || !File.Exists(configFilePath))
{
throw new ArgumentNullException("日志配置文件不存在");
}
XmlConfigurator.ConfigureAndWatch(new FileInfo(configFilePath));
}
}
Global.asax文件配置Log4Net 加一行代码
Log4NetHelper.LoadConfig(AppDomain.CurrentDomain.BaseDirectory + "Web.config");
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WebApplication1.Helper;
namespace WebApplication1
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
Log4NetHelper.LoadConfig(AppDomain.CurrentDomain.BaseDirectory + "Web.config");
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
运行代码,在Home控制器index方法中测试
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Helper;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Log4NetHelper.logIndex.Info("正常日志");
try
{
int readValue = int.Parse("haha");
}
catch (Exception ex)
{
Log4NetHelper.logIndex.Info("异常日志:" + ex);
}
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
好了,项目的 Logs\Index就有刚才运行产生的日志文件了,当然了,这个路径是第3步web.config配置的。
INFO 2019-07-13 15:02:48,369 [9 ] Index - 正常日志
INFO 2019-07-13 15:02:48,398 [9 ] Index - 异常日志:System.FormatException: 输入字符串的格式不正确。
在 System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
在 System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
在 System.Int32.Parse(String s)
在 WindowsFormsApplication1.Form1.button1_Click(Object sender, EventArgs e) 位置 C:\Users\Administrator\Desktop\test\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:行号 26