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>