Log4net 数据库存储(四)

1.新建一个空的ASP.Net 空项目,然后添加Default.aspx窗体

2.添加配置文件:log4net.config

  1 <?xml version="1.0" encoding="utf-8"?>
  2 <configuration>
  3 
  4     <system.web>
  5       <compilation debug="true" targetFramework="4.0" />
  6     </system.web>
  7 
  8   <configSections>
  9     <!--添加配置节点-->
 10     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
 11   </configSections>
 12 
 13   <log4net>
 14     <!--定义输出到数据库-->
 15     <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
 16       <!--日志缓存写入条数-->
 17       <!--bufferSize表示批处理的日志事件,可以避免每次日志事件都访问数据库,原本是<bufferSize value="100" />一百条才插入-->
 18       <bufferSize value="1" />
 19       <!--日志数据库连接串-->
 20       <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
 21       <connectionString value="DATABASE=log4netDB;SERVER=DESKTOP-F0T373H\WZH;UID=sa;PWD=18855162320;Connect Timeout=15;" />
 22       <!--日志数据库脚本-->
 23       <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[UserID],[UserName],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger,@UserId,@UserName, @message, @exception)" />
 24       <!--日志时间LogDate -->
 25       <parameter>
 26         <parameterName value="@log_date" />
 27         <dbType value="DateTime" />
 28         <layout type="log4net.Layout.RawTimeStampLayout" />
 29       </parameter>
 30       <parameter>
 31         <parameterName value="@thread" />
 32         <dbType value="String" />
 33         <size value="255" />
 34         <layout type="log4net.Layout.PatternLayout">
 35           <conversionPattern value="%thread" />
 36         </layout>
 37       </parameter>
 38       <!--日志类型LogLevel -->
 39       <parameter>
 40         <parameterName value="@log_level" />
 41         <dbType value="String" />
 42         <size value="50" />
 43         <layout type="log4net.Layout.PatternLayout">
 44           <conversionPattern value="%level" />
 45         </layout>
 46       </parameter>
 47       <!--日志对象LogLogger -->
 48       <parameter>
 49         <parameterName value="@logger" />
 50         <dbType value="String" />
 51         <size value="255" />
 52         <layout type="log4net.Layout.PatternLayout">
 53           <conversionPattern value="%logger" />
 54         </layout>
 55       </parameter>
 56       <!--自定义UserId -->
 57       <parameter>
 58         <parameterName value="@UserId" />
 59         <dbType value="String" />
 60         <size value="20" />
 61         <layout type="log4net保存到数据库中.MyLayout">
 62           <conversionPattern value="%Property{UserID}" />
 63         </layout>
 64       </parameter>
 65       <!--自定义UserName -->
 66       <parameter>
 67         <parameterName value="@UserName" />
 68         <dbType value="String" />
 69         <size value="50" />
 70         <layout type="log4net保存到数据库中.MyLayout">
 71           <conversionPattern value="%Property{UserName}" />
 72         </layout>
 73       </parameter>
 74       <!--日志信息Message -->
 75       <!--<parameter>
 76         <parameterName value="@message" />
 77         <dbType value="String" />
 78         <size value="4000" />
 79         <layout type="log4net.Layout.PatternLayout">
 80           <conversionPattern value="%message" />
 81         </layout>
 82       </parameter>-->
 83       <!--自定义Message -->
 84       <parameter>
 85         <parameterName value="@Message" />
 86         <dbType value="String" />
 87         <size value="200" />
 88         <layout type="log4net保存到数据库中.MyLayout">
 89           <conversionPattern value="%Property{Message}" />
 90         </layout>
 91       </parameter>
 92       <!--异常信息Exception -->
 93       <parameter>
 94         <parameterName value="@exception" />
 95         <dbType value="String" />
 96         <size value="2000" />
 97         <layout type="log4net.Layout.ExceptionLayout" />
 98       </parameter>
 99     </appender>
100     <root>
101       <!--配置可输出日志级别-->
102       <level value="all"/>
103       <!--应用配置-->
104       <appender-ref ref="AdoNetAppender"/>
105     </root>
106   </log4net>
107   
108 </configuration>

3.在项目中的Properties中AssemblyInfo.cs的末尾添加
 1 [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]  

4.添加实体类:LogEntity.cs 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 
 6 namespace log4net保存到数据库中
 7 {
 8     public class LogEntity
 9     {
10         public string UserID { get; set; }
11         public string UserName { get; set; }
12 
13         public string Message { get; set; }
14     }
15 }
View Code

5.添加扩展类:MyPatternConverter.cs , MyLayout.cs 来扩展PatternLayout

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using log4net.Layout.Pattern;
 6 using System.Reflection;
 7 
 8 namespace log4net保存到数据库中
 9 {
10     public class MyPatternConverter:PatternLayoutConverter
11     {
12         protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
13         {
14             if (Option != null)
15                 WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
16             else
17                 WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
18         }
19 
20         //通过反射获取传入的日志对象的某个属性的值
21         private object LookupProperty(string property,log4net.Core.LoggingEvent loggingEvent)
22         {
23             object propertyvalue = string.Empty;
24             PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);
25 
26             if (propertyInfo != null)
27                 propertyvalue = propertyInfo.GetValue(loggingEvent.MessageObject, null);
28             return propertyvalue;
29         }
30     }
31 }
MyPatternConverter.cs
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using log4net.Layout;
 6 
 7 namespace log4net保存到数据库中
 8 {
 9     public class MyLayout:PatternLayout
10     {
11         public MyLayout()
12         {
13             this.AddConverter("Property", typeof(MyPatternConverter));
14         }
15     }
16 }
MyLayout.cs

6.添加使用类:LogHelper.cs

  1 using System;
  2 using System.Diagnostics;
  3 using System.IO;
  4 
  5 using log4net;
  6 
  7 namespace log4net保存到数据库中
  8 {
  9     public class LogHelper
 10     {
 11         /// <summary>
 12         /// LoggerName
 13         /// </summary>
 14         public static string LoggerName = string.Empty;
 15         /// <summary>
 16         /// 用户ID
 17         /// </summary>
 18         public static string UserID = string.Empty;
 19         /// <summary>
 20         /// 用户名称
 21         /// </summary>
 22         public static string UserName = string.Empty;
 23 
 24         private static ILog iLog;
 25         private static LogEntity logEntity;
 26 
 27         /// <summary>
 28         /// 接口
 29         /// </summary>
 30         private static ILog log
 31         {
 32             get
 33             {
 34 
 35                 if (iLog == null)
 36                 {
 37                     iLog = log4net.LogManager.GetLogger(LoggerName);
 38                 }
 39                 else
 40                 {
 41                     if (iLog.Logger.Name != LoggerName)
 42                     {
 43                         iLog = log4net.LogManager.GetLogger(LoggerName);
 44                     }
 45                 }
 46 
 47                 return iLog;
 48             }
 49         }
 50 
 51         /// <summary>
 52         /// 构造消息实体
 53         /// </summary>
 54         /// <param name="message"></param>
 55         /// <returns></returns>
 56         private static LogEntity BuildMessageMode(string message)
 57         {
 58             if (logEntity == null)
 59             {
 60                 logEntity = new LogEntity();
 61                 logEntity.UserID = UserID;
 62                 logEntity.UserName = UserName;
 63                 logEntity.Message = message;
 64             }
 65             else
 66                 logEntity.Message = message;
 67 
 68             return logEntity;
 69         }
 70 
 71         /// <summary>
 72         /// 调试
 73         /// </summary>
 74         /// <param name="message">消息</param>
 75         public static void Debug(string message)
 76         {
 77             if (log.IsDebugEnabled)
 78                 log.Debug(BuildMessageMode(message));
 79         }
 80 
 81         /// <summary>
 82         /// 调试
 83         /// </summary>
 84         /// <param name="message">消息</param>
 85         /// <param name="exception">异常</param>
 86         public static void Debug(string message, Exception ex)
 87         {
 88             if (log.IsDebugEnabled)
 89                 log.Debug(BuildMessageMode(message), ex);
 90         }
 91 
 92         /// <summary>
 93         /// 信息
 94         /// </summary>
 95         /// <param name="message">消息</param>
 96         public static void Info(string message)
 97         {
 98             if (log.IsInfoEnabled)
 99                 log.Info(BuildMessageMode(message));
100         }
101 
102         /// <summary>
103         /// 信息
104         /// </summary>
105         /// <param name="message">消息</param>
106         /// <param name="exception">异常</param>
107         public static void Info(string message, Exception ex)
108         {
109             if (log.IsInfoEnabled)
110                 log.Info(BuildMessageMode(message), ex);
111         }
112 
113         /// <summary>
114         /// 一般错误
115         /// </summary>
116         /// <param name="message">消息</param>
117         public static void Error(string message)
118         {
119             if (log.IsErrorEnabled)
120                 log.Error(BuildMessageMode(message));
121         }
122 
123         /// <summary>
124         /// 一般错误
125         /// </summary>
126         /// <param name="message">消息</param>
127         /// <param name="exception">异常</param>
128         public static void Error(string message, Exception exception)
129         {
130             if (log.IsErrorEnabled)
131                 log.Error(BuildMessageMode(message), exception);
132         }
133 
134         /// <summary>
135         /// 警告
136         /// </summary>
137         /// <param name="message">消息</param>
138         public static void Warn(string message)
139         {
140             if (log.IsWarnEnabled)
141                 log.Warn(BuildMessageMode(message));
142         }
143 
144         /// <summary>
145         /// 警告
146         /// </summary>
147         /// <param name="message">消息</param>
148         /// <param name="exception">异常</param>
149         public static void Warn(string message, Exception ex)
150         {
151             if (log.IsWarnEnabled)
152                 log.Warn(BuildMessageMode(message), ex);
153         }
154 
155         /// <summary>
156         /// 严重
157         /// </summary>
158         /// <param name="message">消息</param>
159         public static void Fatal(string message)
160         {
161             if (log.IsFatalEnabled)
162                 log.Fatal(BuildMessageMode(message));
163         }
164 
165         /// <summary>
166         /// 严重
167         /// </summary>
168         /// <param name="message">消息</param>
169         /// <param name="exception">异常</param>
170         public static void Fatal(string message, Exception ex)
171         {
172             if (log.IsFatalEnabled)
173                 log.Fatal(BuildMessageMode(message), ex);
174         }
175     }
176 }
LogHelper.cs

7.在Default.aspx.cs中使用:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 using log4net;
 8 
 9 namespace log4net保存到数据库中
10 {
11     public partial class Default : System.Web.UI.Page
12     {
13         protected void Page_Load(object sender, EventArgs e)
14         {
15             LogHelper.LoggerName = typeof(Default).ToString();
16             LogHelper.UserID = "12345";
17             LogHelper.UserName = "me";
18             int i = 0;
19             try
20             {
21                 
22                 int b = 3 / i;
23             }
24             catch (Exception ex)
25             {
26                 LogHelper.Error(ex.Message, ex);
27             }
28             LogHelper.Fatal("Fatal",new Exception("异常信息"));
29             LogHelper.Info("Info");
30             LogHelper.Warn("Warn");
31             LogHelper.Debug("Debug");
32         }
33     }
34 }
Default.aspx.cs

8.配置数据库SQL Server2012:创建数据库log4netDB

 1 CREATE TABLE [dbo].[Log] (
 2     [Id] [int] IDENTITY (1, 1) NOT NULL,
 3     [Date] [datetime] NOT NULL,
 4     [Thread] [varchar] (255) NOT NULL,
 5     [Level] [varchar] (50) NOT NULL,
 6     [Logger] [varchar] (255) NOT NULL,
 7     [UserID] [varchar] (20) NOT NULL,
 8     [UserName] [varchar] (50) NOT NULL,
 9     [Message] [varchar] (4000) NOT NULL,
10     [Exception] [varchar] (2000) NULL
11 )
sql语句

9.运行

 10.帮助文档:

http://www.cnblogs.com/izreo/p/5651139.html

http://www.cnblogs.com/jiajinyi/p/5884930.html

posted @ 2018-02-06 00:13  All_just_for_fun  阅读(1131)  评论(0编辑  收藏  举报