log4Net作為專業的log記錄控制項,對於它的強大功能大家一定不陌生。下麵我將詳細介紹如何利用其自定義屬性,讓日誌信息更完整。一,創建測試工程,log4Net組件可以自己從網上下載,也可通過Nuget進行安裝。 二,創建日誌模型及資料庫表,因為我們的日誌信息可以輸出為文本,也可以輸出到資料庫。三, ...
log4Net作為專業的log記錄控制項,對於它的強大功能大家一定不陌生。下麵我將詳細介紹如何利用其自定義屬性,讓日誌信息更完整。
一,創建測試工程,log4Net組件可以自己從網上下載,也可通過Nuget進行安裝。
二,創建日誌模型及資料庫表,因為我們的日誌信息可以輸出為文本,也可以輸出到資料庫。
三,添加MyLayout,MyPatternConverter類擴展PatternLayout。
四,添加Log4Net.config文件,進行輸入方式定義。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<log4net>
<!-- ConversionPattern 解釋
%m(message):輸出的日誌消息,如ILog.Debug(…)輸出的一條消息
%n(new line):換行
%d(datetime):輸出當前語句運行的時刻
%r(run time):輸出程式從運行到執行到當前語句時消耗的毫秒數
%t(thread id):當前語句所在的線程ID
%p(priority): 日誌的當前優先順序別,即DEBUG、INFO、WARN…等
%c(class):當前日誌對象的名稱
%L:輸出語句所在的行號
%F:輸出語句所在的文件名
%-數字:表示該項的最小長度,如果不夠,則用空格填充
-->
<!--定義輸出到控制台命令行中-->
<logger name="myLogger">
<level value="ALL"/>
<appender-ref ref="ConsoleAppender" />
</logger>
<!--定義輸出到控制台命令行中-->
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="Log4NetTest.MyLayout">
<param name="ConversionPattern" value="日誌時間:%d %n日誌級別:%-5p %n用 戶 ID:%Property{UserID} %n用戶姓名:%Property{UserName} %n日誌信息:%Property{Message} %n異常信息:%exception %n%n" />
</layout>
</appender>
<!--定義輸出到windows事件中-->
<appender name="WindowsAppender" type="log4net.Appender.EventLogAppender">
<layout type="Log4NetTest.MyLayout">
<param name="ConversionPattern" value="日誌時間:%d %n日誌級別:%-5p %n用 戶 ID:%Property{UserID} %n用戶姓名:%Property{UserName} %n日誌信息:%Property{Message} %n異常信息:%exception %n%n" />
</layout>
</appender>
<!--定義輸出到文件中-->
<appender name="TextAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\\" />
<param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value="yyyyMMdd" />
<param name="RollingStyle" value="Date" />
<layout type="Log4NetTest.MyLayout">
<param name="ConversionPattern" value="日誌時間:%d %n日誌級別:%-5p %n用 戶 ID:%Property{UserID} %n用戶姓名:%Property{UserName} %n日誌信息:%Property{Message} %n異常信息:%exception %n%n" />
</layout>
</appender>
<!--定義輸出到資料庫-->
<appender name="DataBaseAppender" type="log4net.Appender.AdoNetAppender">
<!--日誌緩存寫入條數-->
<bufferSize value="1" />
<!--日誌資料庫連接串-->
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=.\SQL2008;initial catalog=Demo;integrated security=false;persist security info=True;User ID=sa;Password=1qaz" />
<!--日誌資料庫腳本-->
<commandText value="INSERT INTO LogInfo ([LogDate],[LogLevel],[UserId],[UserName],[Message],[Exception]) VALUES (@LogDate, @LogLevel,@UserId,@UserName, @Message, @Exception)" />
<!--日誌時間LogDate -->
<parameter>
<parameterName value="@LogDate" />
<dbType value="String" />
<size value="30" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{yyyy-MM-dd HH:mm:ss}" />
</layout>
</parameter>
<!--日誌類型LogLevel -->
<parameter>
<parameterName value="@LogLevel" />
<dbType value="String" />
<size value="10" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<!--自定義UserId -->
<parameter>
<parameterName value="@UserId" />
<dbType value="String" />
<size value="20" />
<layout type="Log4NetTest.MyLayout">
<conversionPattern value="%Property{UserID}" />
</layout>
</parameter>
<!--自定義UserName -->
<parameter>
<parameterName value="@UserName" />
<dbType value="String" />
<size value="50" />
<layout type="Log4NetTest.MyLayout">
<conversionPattern value="%Property{UserName}" />
</layout>
</parameter>
<!--自定義Message -->
<parameter>
<parameterName value="@Message" />
<dbType value="String" />
<size value="200" />
<layout type="Log4NetTest.MyLayout">
<conversionPattern value="%Property{Message}" />
</layout>
</parameter>
<!--異常信息Exception -->
<parameter>
<parameterName value="@Exception" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
</log4net>
</configuration>
五,添加LogHelper.cs類進行各自信息的寫入操作。
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using log4net;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace Log4NetTest
{
public class LogHelper
{
/// <summary>
/// LoggerName
/// </summary>
public static string LoggerName = string.Empty;
/// <summary>
/// 用戶ID
/// </summary>
public static string UserID = string.Empty;
/// <summary>
/// 用戶名稱
/// </summary>
public static string UserName = string.Empty;
private static ILog iLog;
private static LogEntity logEntity;
/// <summary>
/// 介面
/// </summary>
private static ILog log
{
get
{
string path = Application.StartupPath + @"\Log4Net.config";
log4net.Config.XmlConfigurator.Configure(new FileInfo(path));
if (iLog == null)
{
iLog = log4net.LogManager.GetLogger(LoggerName);
}
else
{
if (iLog.Logger.Name != LoggerName)
{
iLog = log4net.LogManager.GetLogger(LoggerName);
}
}
return iLog;
}
}
/// <summary>
/// 構造消息實體
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
private static LogEntity BuildMessageMode(string message)
{
if (logEntity == null)
{
logEntity = new LogEntity();
logEntity.UserID = UserID;
logEntity.UserName = UserName;
logEntity.Message = message;
}
else
logEntity.Message = message;
return logEntity;
}
/// <summary>
/// 調試
/// </summary>
/// <param name="message">消息</param>
public static void Debug(string message)
{
if (log.IsDebugEnabled)
log.Debug(BuildMessageMode(message));
}
/// <summary>
/// 調試
/// </summary>
/// <param name="message">消息</param>
/// <param name="exception">異常</param>
public static void Debug(string message, Exception ex)
{
if (log.IsDebugEnabled)
log.Debug(BuildMessageMode(message), ex);
}
/// <summary>
/// 信息
/// </summary>
/// <param name="message">消息</param>
public static void Info(string message)
{
if (log.IsInfoEnabled)
log.Info(BuildMessageMode(message));
}
/// <summary>
/// 信息
/// </summary>
/// <param name="message">消息</param>
/// <param name="exception">異常</param>
public static void Info(string message, Exception ex)
{
if (log.IsInfoEnabled)
log.Info(BuildMessageMode(message), ex);
}
/// <summary>
/// 一般錯誤
/// </summary>
/// <param name="message">消息</param>
public static void Error(string message)
{
if (log.IsErrorEnabled)
log.Error(BuildMessageMode(message));
}
/// <summary>
/// 一般錯誤
/// </summary>
/// <param name="message">消息</param>
/// <param name="exception">異常</param>
public static void Error(string message, Exception exception)
{
if (log.IsErrorEnabled)
log.Error(BuildMessageMode(message), exception);
}
/// <summary>
/// 警告
/// </summary>
/// <param name="message">消息</param>
public static void Warn(string message)
{
if (log.IsWarnEnabled)
log.Warn(BuildMessageMode(message));
}
/// <summary>
/// 警告
/// </summary>
/// <param name="message">消息</param>
/// <param name="exception">異常</param>
public static void Warn(string message, Exception ex)
{
if (log.IsWarnEnabled)
log.Warn(BuildMessageMode(message), ex);
}
/// <summary>
/// 嚴重
/// </summary>
/// <param name="message">消息</param>
public static void Fatal(string message)
{
if (log.IsFatalEnabled)
log.Fatal(BuildMessageMode(message));
}
/// <summary>
/// 嚴重
/// </summary>
/// <param name="message">消息</param>
/// <param name="exception">異常</param>
public static void Fatal(string message, Exception ex)
{
if (log.IsFatalEnabled)
log.Fatal(BuildMessageMode(message), ex);
}
}
}
六,進行日誌效果測試,只要通過修改Log4Net.config,就可實現各種方式的輸入。
輸出到控制台:
<logger name="myLogger">
<level value="ALL"/>
<appender-ref ref="ConsoleAppender" />
</logger>
輸出到文件:
<logger name="myLogger">
<level value="ALL"/>
<appender-ref ref="TextAppender" />
</logger>
輸出到資料庫:
<logger name="myLogger">
<level value="ALL"/>
<appender-ref ref="DataBaseAppender" />
</logger>