log4net的C#封裝類
log4net是net界知名的日誌管理系統,開源的。它的用法適合各種環境異常、錯誤、日誌等的記錄和管理,但是同樣它諸多的方法函式讓初學者望而生畏。這裡的C#封裝類實現了log4net的二次封裝,對於日常的日誌管理足夠便利了。
封裝說明:
1.使用靜態方法呼叫即可寫入日誌。
2.在日誌資訊寫入之前,定義委託處理日誌資訊,便於記錄日誌資訊之前,顯示給使用者。
3.新增程式碼配置Log4net,避免應用程式總是攜帶配置檔案。如果需要使用配置檔案,即可在AssemblyInfo.cs新增
[assembly: log4net.Config.XMLConfigurator(ConfigFile = "log.xml", Watch = false)]
封裝類:
using System;
using System.Data;
using System.Text;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Layout;
using log4net.Repository.Hierarchy;
namespace Chen.Common
{
public class Log4NetHelp
{
#region 變數定義
//定義資訊的二次處理
public static event Action<string> OutputMessage;
//ILog物件
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//記錄異常日誌資料庫連線字串
private const string _ConnectionString = @"data source=your server;initial catalog=your db;integrated security=false;persist security info=True;User ID=sa;Pass
//資訊模板
private const string _ConversionPattern = "%n【記錄時間】%date%n【描述】%message%n";
#endregion
#region 定義資訊二次處理方式
private static void HandMessage(object Msg)
{
if (OutputMessage != null)
{
OutputMessage(Msg.ToString());
}
}
private static void HandMessage(object Msg, Exception ex)
{
if (OutputMessage != null)
{
OutputMessage(string.Format("{0}:{1}", Msg.ToString(), ex.ToString()));
}
}
private static void HandMessage(string format, params object[] args)
{
if (OutputMessage != null)
{
OutputMessage(string.Format(format, args));
}
}
#endregion
#region 封裝Log4net
public static void Debug(object message)
{
HandMessage(message);
if (log.IsDebugEnabled)
{
log.Debug(message);
}
}
public static void Debug(object message, Exception ex)
{
HandMessage(message, ex);
if (log.IsDebugEnabled)
{
log.Debug(message, ex);
}
}
public static void DebugFormat(string format, params object[] args)
{
HandMessage(format, args);
if (log.IsDebugEnabled)
{
log.DebugFormat(format, args);
}
}
public static void Error(object message)
{
HandMessage(message);
if (log.IsErrorEnabled)
{
log.Error(message);
}
}
public static void Error(object message, Exception ex)
{
HandMessage(message, ex);
if (log.IsErrorEnabled)
{
log.Error(message, ex);
}
}
public static void ErrorFormat(string format, params object[] args)
{
HandMessage(format, args);
if (log.IsErrorEnabled)
{
log.ErrorFormat(format, args);
}
}
public static void Fatal(object message)
{
HandMessage(message);
if (log.IsFatalEnabled)
{
log.Fatal(message);
}
}
public static void Fatal(object message, Exception ex)
{
HandMessage(message, ex);
if (log.IsFatalEnabled)
{
log.Fatal(message, ex);
}
}
public static void FatalFormat(string format, params object[] args)
{
HandMessage(format, args);
if (log.IsFatalEnabled)
{
log.FatalFormat(format, args);
}
}
public static void Info(object message)
{
HandMessage(message);
if (log.IsInfoEnabled)
{
log.Info(message);
}
}
public static void Info(object message, Exception ex)
{
HandMessage(message, ex);
if (log.IsInfoEnabled)
{
log.Info(message, ex);
}
}
public static void InfoFormat(string format, params object[] args)
{
HandMessage(format, args);
if (log.IsInfoEnabled)
{
log.InfoFormat(format, args);
}
}
public static void Warn(object message)
{
HandMessage(message);
if (log.IsWarnEnabled)
{
log.Warn(message);
}
}
public static void Warn(object message, Exception ex)
{
HandMessage(message, ex);
if (log.IsWarnEnabled)
{
log.Warn(message, ex);
}
}
public static void WarnFormat(string format, params object[] args)
{
HandMessage(format, args);
if (log.IsWarnEnabled)
{
log.WarnFormat(format, args);
}
}
#endregion
#region 手動載入配置
public static void LoadADONetAppender()
{
Hierarchy hier = LogManager.GetLoggerRepository() as log4net.Repository.Hierarchy.Hierarchy;
if (hier != null)
{
log4net.Appender.AdoNetAppender appender = new log4net.Appender.AdoNetAppender();
appender.Name = "AdoNetAppender";
appender.CommandType = CommandType.Text;
appender.BufferSize = 1;
appender.ConnectionType = "System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
appender.ConnectionString = _ConnectionString;
appender.CommandText = @"INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)";
appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@log_date", DbType = System.Data.DbType.DateTime, Layout = new log4net.Layout.RawTimeStampLayout() });
appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@thread", DbType = System.Data.DbType.String, Size = 255, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%thread")) });
appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@log_level", DbType = System.Data.DbType.String, Size = 50, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%level")) });
appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@logger", DbType = System.Data.DbType.String, Size = 255, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%logger")) });
appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@message", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%message")) });
appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@exception", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(new ExceptionLayout()) });
appender.ActivateOptions();
BasicConfigurator.Configure(appender);
}
}
public static void LoadFileAppender()
{
FileAppender appender = new FileAppender();
appender.Name = "FileAppender";
appender.File = "error.log";
appender.AppendToFile = true;
PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = _ConversionPattern;
patternLayout.ActivateOptions();
appender.Layout = patternLayout;
//選擇UTF8編碼,確保中文不亂碼。
appender.Encoding = Encoding.UTF8;
appender.ActivateOptions();
BasicConfigurator.Configure(appender);
}
public static void LoadRollingFileAppender()
{
RollingFileAppender appender = new RollingFileAppender();
appender.AppendToFile = true;
appender.Name = "RollingFileAppender";
appender.DatePattern = "yyyy-MM-dd HH'時.log'";
appender.File = "Logs/";
appender.AppendToFile = true;
appender.RollingStyle = RollingFileAppender.RollingMode.Composite;
appender.MaximumFileSize = "500kb";
appender.MaxSizeRollBackups = 10;
appender.StaticLogFileName = false;
PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = _ConversionPattern;
patternLayout.ActivateOptions();
appender.Layout = patternLayout;
//選擇UTF8編碼,確保中文不亂碼。
appender.Encoding = Encoding.UTF8;
appender.ActivateOptions();
BasicConfigurator.Configure(appender);
}
public static void LoadConsoleAppender()
{
ConsoleAppender appender = new ConsoleAppender();
appender.Name = "ConsoleAppender";
PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = _ConversionPattern;
patternLayout.ActivateOptions();
appender.Layout = patternLayout;
appender.ActivateOptions();
BasicConfigurator.Configure(appender);
}
public static void LoadTraceAppender()
{
TraceAppender appender = new TraceAppender();
appender.Name = "TraceAppender";
PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = _ConversionPattern;
patternLayout.ActivateOptions();
appender.Layout = patternLayout;
appender.ActivateOptions();
BasicConfigurator.Configure(appender);
}
public static void LoadEventLogAppender()
{
EventLogAppender appender = new EventLogAppender();
appender.Name = "EventLogAppender";
PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = _ConversionPattern;
patternLayout.ActivateOptions();
appender.Layout = patternLayout;
appender.ActivateOptions();
BasicConfigurator.Configure(appender);
}
#endregion
#region 定義常規應用程式中未處理的異常資訊記錄方式
public static void LoadUnhandledException()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler
((sender, e) =>
{
log.Fatal("未處理的異常", e.ExceptionObject as Exception);
});
}
#endregion
}
}
對應的配置xml檔案:
log.xml
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
</configSections>
<log4net>
<!--定義輸出到檔案中-->
<appender name="SysAppender" type="log4net.Appender.RollingFileAppender">
<!--日誌的路徑-->
<file value="Logs/" />
<!--是否覆蓋,預設是追加true-->
<appendToFile value="true"/>
<rollingStyle value="Composite"/>
<!--檔名稱-->
<DatePattern value="yyyy-MM-dd HH'時.log'"></DatePattern>
<!--設定無限備份=-1 ,最大備份數為1000-->
<param name="MaxSizeRollBackups" value="1000"/>
<!--每個檔案的大小-->
<param name="MaximumFileSize" value="500KB"/>
<!--名稱是否可以更改 為false為可以更改-->
<param name="StaticLogFileName" value="false"/>
<layout type="log4net.Layout.PatternLayout">
<!--輸出格式-->
<conversionPattern value="%n【記錄時間】%date%n【描述】%message%n"/>
</layout>
</appender>
<!--定義輸出到控制檯命令列中-->
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n【記錄時間】%date%n【描述】%message%n"/>
</layout>
</appender>
<!--定義輸出到windows事件中-->
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n==========
%n【日誌級別】%-5level
%n【記錄時間】%date
%n【執行緒編號】[%thread]
%n【執行時間】[%r]毫秒
%n【出錯檔案】%F
%n【出錯行號】%L
%n【出錯的類】%logger 屬性[%property{NDC}]
%n【錯誤描述】%message
%n【錯誤詳情】%newline"/>
</layout>
</appender>
<!--定義輸出到Trace中-->
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<!--<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />-->
<conversionPattern value="%n==========
%n【日誌級別】%-5level
%n【記錄時間】%date
%n【執行緒編號】[%thread]
%n【執行時間】[%r]毫秒
%n【出錯檔案】%F
%n【出錯行號】%L
%n【出錯的類】%logger 屬性[%property{NDC}]
%n【錯誤描述】%message
%n【錯誤詳情】%newline"/>
</layout>
</appender>
<!--定義日誌的輸出媒介,下面定義日誌以四種方式輸出。也可以下面的按照一種型別或其他型別輸出。-->
<root>
<!--日誌的級別 OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL 只有日誌輸出級別大於或等於配置的級別才能輸出日誌資訊-->
<level value="ALL" />
<!--檔案形式記錄日誌-->
<appender-ref ref="SysAppender"/>
<!--控制檯控制顯示日誌-->
<appender-ref ref="ConsoleAppender"/>
<!--Windows事件日誌-->
<!--<appender-ref ref="EventLogAppender"/>-->
<!--TraceAppender日誌-->
<!--<appender-ref ref="TraceAppender"/>-->
</root>
</log4net>
</configuration>