封装说明:

  1.使用静态方法调用即可写入日志。

  2.在日志信息写入之前,定义委托处理日志信息,便于记录日志信息之前,显示给用户。

  3.添加代码配置Log4net,避免应用程序总是携带配置文件。如果需要使用配置文件,即可在AssemblyInfo.cs添加

    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log.xml", Watch = false)]
展开代码

/* ==============================================================================
* 文 件 名:Log4NetHelp
* 功能描述:Log4Net二次封装类
* Copyright (c) 2012 武汉经纬视通科技有限公司
* 创 建 人: chenbo
* 创建时间: 2013/2/19 14:15:44
* 修 改 人:
* 修改时间:
* 修改描述:
* 版 本: V1.0.0.001
* ==============================================================================*/
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;Password=1111";
//信息模板
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 = ;
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 = , Layout = new Layout2RawLayoutAdapter(new PatternLayout("%thread")) });
appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@log_level", DbType = System.Data.DbType.String, Size = , Layout = new Layout2RawLayoutAdapter(new PatternLayout("%level")) });
appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@logger", DbType = System.Data.DbType.String, Size = , Layout = new Layout2RawLayoutAdapter(new PatternLayout("%logger")) });
appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@message", DbType = System.Data.DbType.String, Size = , Layout = new Layout2RawLayoutAdapter(new PatternLayout("%message")) });
appender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@exception", DbType = System.Data.DbType.String, Size = , 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 = ;
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
}
}
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>
<!--设置无限备份=- ,最大备份数为1000-->
<param name="MaxSizeRollBackups" value=""/>
<!--每个文件的大小-->
<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>

log4net封装类 zz的更多相关文章

  1. Colour your Log4Net events in your RichTextBox zz

    You’re most probably here because you have already read my article How to watch your log through you ...

  2. log4net部分配置说明

    第一步: 添加并应用Log4net.dll.然后在Web.config文件中添加下面的配置局 <configSections>     <section name="log ...

  3. Log4Net组件的应用详解

    第一步: 添加并应用Log4net.dll.然后在Web.config文件中添加下面的配置局 <configSections>    <section name="log4 ...

  4. (转)非常完善的Log4net详细说明

    转自:http://www.cnblogs.com/zhangchenliang/p/4546352.htmlhttp://www.cnblogs.com/zhangchenliang/p/45463 ...

  5. 非常完善的Log4net详细说明

      4.1.6 <filter> 过滤器,只能作为<appender>的子元素. 支持的属性: type 必须的,Filter的类型 支持的子元素: param 0个或多个,  ...

  6. log4net详解(转载)

    1.概述 log4net是.Net下一个非常优秀的开源日志记录组件.log4net记录日志的功能非常强大.它可以将日志分不同的等级,以不同的格式,输出到不同的媒介.本文主要是介绍如何在Visual S ...

  7. log4net详细配置说明

    原文地址:http://blog.sina.com.cn/s/blog_671486bc01011rdj.html 1.概述 log4net是.Net下一个非常优秀的开源日志记录组件.log4net记 ...

  8. [转载]非常完善的Log4net详细说明

    前言 此篇文章是我见过写得最好的一片关于Log4Net的文章,内容由简入难,而且面面俱到,堪称入门和精通的佳作,特从懒惰的肥兔的转载过来. 1.概述 log4net是.Net下一个非常优秀的开源日志记 ...

  9. [转]log4net使用(WinForm/WebFrom)

    原来的一篇文章,今天用 WLW 转到页面上,原文章以及附件下载地址:http://zhq.ahau.edu.cn/blog/article.asp?id=366 http://www.cnblogs. ...

随机推荐

  1. 初识Angular2

    Angular2是面向未来的科技,要求浏览器支持ES6+,我们现在要尝试的话,需要加一些 垫片来抹平当前浏览器与ES6的差异: angular2-polyfills - 为ES5浏览器提供ES6特性支 ...

  2. spring mvc 笔记

    springmvc 课堂笔记 1.Springmvc是什么 Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想, ...

  3. ubuntu netbeans compile ygopro client with google protobuf lib

    environment: ubuntu 16.04 netbeans 8.2 ygopro Fluorohydride with Irrlicht Game Engine 问题1: google pr ...

  4. Source Insight及常用插件

    Source Insight及常用插件 1.Source Insight 2.插件 <1>.使用快捷键注释,单行注释,多行注释,#if 0注释 <2>.跳转到当前文件所在的文件 ...

  5. (转) IOS用CGContextRef画各种图形(文字、圆、直线、弧线、矩形、扇形、椭圆、三角形、圆角矩形、贝塞尔曲线、图片)

    首先了解一下CGContextRef: An opaque type that represents a Quartz 2D drawing environment. Graphics Context ...

  6. ECMA5.1中关于encodeURI,decodeURI 和encodeComponentURI,decodeComponentURI的区别

    The encodeURI and decodeURI functions are intended to work with complete URIs; theyassume that any r ...

  7. 一个供新手把玩的jQueryUI在线文档

    最近整理了一份jQueryUI文档,方便以后学习和运用. 把玩地址

  8. centos 交换分区

    内容来自:http://www.huzs.net/?p=1683 一般在桌面型的用不到,因为现在内存都比较大,服务器就不一样了,但是建议无论是在桌面还是服务器上,都设置 swap 以下操作都是在 ro ...

  9. Oracle数据库小知识,改数据库数据

    在一张表上面右键-->查询数据,会生成sql语句,表后面带有t,表示模糊查询, 后面跟上for update之后,执行语句-->小锁(编辑数据)就可以修改数据里面的数据了,修改之后--&g ...

  10. sea.js,spm学习

    安装spm 下载sea.js 运行spm npm install spm@2.x -g npm install spm-build -g 下载sea.js git clone https://gith ...