log4net简单用法
一、NuGet在Server,mvc中添加Common.Logging和common.Logging.Log4Net如下图
二、在Server层创建logger类
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<!--级别层级ALL<DEBUG<INFO<WARN<ERROR<FATAL<OFF -->
<!--调试日志-->
<appender name="debugLog" type="log4net.Appender.RollingFileAppender,log4net" >
<param name="File" value="logs\debug\debug.log" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Date" />
<param name="DatePattern" value="yyyyMMdd" />
<param name="StaticLogFileName" value="true" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}%newline%message%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="DEBUG" />
<param name="LevelMax" value="DEBUG" />
</filter>
</appender> <!--信息日志-->
<appender name="infoLog" type="log4net.Appender.RollingFileAppender,log4net" >
<param name="File" value="logs\info\info.log" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Date" />
<param name="DatePattern" value="yyyyMMdd" />
<param name="StaticLogFileName" value="true" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="INFO" />
<param name="LevelMax" value="INFO" />
</filter>
</appender> <!--错误日志-->
<appender name="errorLog" type="log4net.Appender.RollingFileAppender,log4net" >
<param name="File" value="logs\error\error.log" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Date" />
<param name="DatePattern" value="yyyyMMdd" />
<param name="StaticLogFileName" value="true" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}%newline%message%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="ERROR" />
<param name="LevelMax" value="ERROR" />
</filter>
</appender>
<!--警告日志-->
<appender name="warnLog" type="log4net.Appender.RollingFileAppender,log4net" >
<param name="File" value="logs\warn\warn.log" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Date" />
<param name="DatePattern" value="yyyyMMdd" />
<param name="StaticLogFileName" value="true" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}%newline%message%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="WARN" />
<param name="LevelMax" value="WARN" />
</filter>
</appender>
<!--致命错误日志-->
<appender name="fatalLog" type="log4net.Appender.RollingFileAppender,log4net" >
<param name="File" value="logs\fatal\fatal.log" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Date" />
<param name="DatePattern" value="yyyyMMdd" />
<param name="StaticLogFileName" value="true" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}%newline%message%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="FATAL" />
<param name="LevelMax" value="FATAL" />
</filter>
</appender> <appender name="LogToDB" 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=oa.ctitech.cn;Initial Catalog=logtest;Persist Security Info=True;User ID=sa;Password=zkx123" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="@exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
<!--<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="DEBUG" />
<param name="LevelMax" value="FATAL" />
</filter>-->
</appender>
<root>
<level value="ALL" />
<appender-ref ref="debugLog" />
<appender-ref ref="infoLog"/>
<appender-ref ref="warnLog" />
<appender-ref ref="errorLog" />
<appender-ref ref="fatalLog" />
<!--<appender-ref ref="LogToDB" />-->
</root>
<!--
CREATE TABLE [dbo].[Log] (
[Id] [int] IDENTITY (1, 1) NOT NULL,
[Date] [datetime] NOT NULL,
[Thread] [varchar] (255) NOT NULL,
[Level] [varchar] (50) NOT NULL,
[Logger] [varchar] (255) NOT NULL,
[Message] [varchar] (4000) NOT NULL,
[Exception] [varchar] (2000) NULL
)
-->
</log4net>
三、在mvc项目中添加log4net.config
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text; namespace LogServer
{
public class Logger
{
#region Wrap common.logging static readonly Common.Logging.ILog log = Common.Logging.LogManager.GetCurrentClassLogger(); public static void Debug(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception)
{
log.Debug(formatProvider, formatMessageCallback, exception);
} public static void Debug(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback)
{
log.Debug(formatProvider, formatMessageCallback);
} public static void Debug(Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception)
{
log.Debug(formatMessageCallback, exception);
} public static void Debug(Action<Common.Logging.FormatMessageHandler> formatMessageCallback)
{
log.Debug(formatMessageCallback);
} public static void Debug(object message, Exception exception)
{
log.Debug(message, exception);
} public static void Debug(object message)
{
log.Debug(message);
} public static void DebugFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
{
log.DebugFormat(formatProvider, format, exception, args);
} public static void DebugFormat(IFormatProvider formatProvider, string format, params object[] args)
{
log.DebugFormat(formatProvider, format, args);
} public static void DebugFormat(string format, Exception exception, params object[] args)
{
log.DebugFormat(format, exception, args);
} public static void DebugFormat(string format, params object[] args)
{
log.DebugFormat(format, args);
} public static void Error(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception)
{
log.Error(formatProvider, formatMessageCallback, exception);
} public static void Error(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback)
{
log.Error(formatProvider, formatMessageCallback);
} public static void Error(Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception)
{
log.Error(formatMessageCallback, exception);
} public static void Error(Action<Common.Logging.FormatMessageHandler> formatMessageCallback)
{
log.Error(formatMessageCallback);
} public static void Error(object message, Exception exception)
{
log.Error(message, exception);
} public static void Error(object message)
{
log.Error(message);
} public static void ErrorFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
{
log.ErrorFormat(formatProvider, format, exception, args);
} public static void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args)
{
log.ErrorFormat(formatProvider, format, args);
} public static void ErrorFormat(string format, Exception exception, params object[] args)
{
log.ErrorFormat(format, exception, args);
} public static void ErrorFormat(string format, params object[] args)
{
log.ErrorFormat(format, args);
} public static void Fatal(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception)
{
log.Fatal(formatProvider, formatMessageCallback, exception);
} public static void Fatal(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback)
{
log.Fatal(formatProvider, formatMessageCallback);
} public static void Fatal(Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception)
{
log.Fatal(formatMessageCallback, exception);
} public static void Fatal(Action<Common.Logging.FormatMessageHandler> formatMessageCallback)
{
log.Fatal(formatMessageCallback);
} public static void Fatal(object message, Exception exception)
{
log.Fatal(message, exception);
} public static void Fatal(object message)
{
log.Fatal(message);
} public static void FatalFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
{
log.FatalFormat(formatProvider, format, exception, args);
} public static void FatalFormat(IFormatProvider formatProvider, string format, params object[] args)
{
log.FatalFormat(formatProvider, format, args);
} public static void FatalFormat(string format, Exception exception, params object[] args)
{
log.FatalFormat(format, exception, args);
} public static void FatalFormat(string format, params object[] args)
{
log.FatalFormat(format, args);
} public static void Info(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception)
{
log.Info(formatProvider, formatMessageCallback, exception);
} public static void Info(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback)
{
log.Info(formatProvider, formatMessageCallback);
} public static void Info(Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception)
{
log.Info(formatMessageCallback, exception);
} public static void Info(Action<Common.Logging.FormatMessageHandler> formatMessageCallback)
{
log.Info(formatMessageCallback);
} public static void Info(object message, Exception exception)
{
log.Info(message, exception);
} public static void Info(object message)
{
log.Info(message);
} public static void InfoFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
{
log.InfoFormat(formatProvider, format, exception, args);
} public static void InfoFormat(IFormatProvider formatProvider, string format, params object[] args)
{
log.InfoFormat(formatProvider, format, args);
} public static void InfoFormat(string format, Exception exception, params object[] args)
{
log.InfoFormat(format, exception, args);
} public static void InfoFormat(string format, params object[] args)
{
log.InfoFormat(format, args);
} public bool IsDebugEnabled
{
get { return IsDebugEnabled; }
} public bool IsErrorEnabled
{
get { return IsErrorEnabled; }
} public bool IsFatalEnabled
{
get { return IsFatalEnabled; }
} public bool IsInfoEnabled
{
get { return IsInfoEnabled; }
} public bool IsTraceEnabled
{
get { return IsTraceEnabled; }
} public bool IsWarnEnabled
{
get { return IsWarnEnabled; }
} public static void Trace(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception)
{
log.Trace(formatProvider, formatMessageCallback, exception);
} public static void Trace(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback)
{
log.Trace(formatProvider, formatMessageCallback);
} public static void Trace(Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception)
{
log.Trace(formatMessageCallback, exception);
} public static void Trace(Action<Common.Logging.FormatMessageHandler> formatMessageCallback)
{
log.Info(formatMessageCallback);
} public static void Trace(object message, Exception exception)
{
log.Info(message, exception);
} public static void Trace(object message)
{
log.Info(message);
} public static void TraceFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
{
log.InfoFormat(formatProvider, format, exception, args);
} public static void TraceFormat(IFormatProvider formatProvider, string format, params object[] args)
{
log.InfoFormat(formatProvider, format, args);
} public static void TraceFormat(string format, Exception exception, params object[] args)
{
log.InfoFormat(format, exception, args);
} public static void TraceFormat(string format, params object[] args)
{
log.InfoFormat(format, args);
} public static void Warn(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception)
{
log.Warn(formatProvider, formatMessageCallback, exception);
} public static void Warn(IFormatProvider formatProvider, Action<Common.Logging.FormatMessageHandler> formatMessageCallback)
{
log.Warn(formatProvider, formatMessageCallback);
} public static void Warn(Action<Common.Logging.FormatMessageHandler> formatMessageCallback, Exception exception)
{
log.Warn(formatMessageCallback, exception);
} public static void Warn(Action<Common.Logging.FormatMessageHandler> formatMessageCallback)
{
log.Warn(formatMessageCallback);
} public static void Warn(object message, Exception exception)
{
log.Warn(message, exception);
} public static void Warn(object message)
{
log.Warn(message);
} public static void WarnFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
{
log.WarnFormat(formatProvider, format, exception, args);
} public static void WarnFormat(IFormatProvider formatProvider, string format, params object[] args)
{
log.WarnFormat(formatProvider, format, args);
} public static void WarnFormat(string format, Exception exception, params object[] args)
{
log.WarnFormat(format, exception, args);
} public static void WarnFormat(string format, params object[] args)
{
log.WarnFormat(format, args);
} #endregion #region logger with Diagnostics public static void TraceReflect(params string[] args)
{
try
{
StackFrame frame = new StackFrame();
MethodBase method = frame.GetMethod();
StackFrame frame2 = new StackFrame();
MethodBase method2 = frame2.GetMethod();
List<string> list = new List<string>();
if (method.DeclaringType != null)
{
string format = GetReflectLogFormat(args, method.DeclaringType.ToString(), method2.Name + "/" + method.Name, ref list);
Logger.TraceFormat(format, list.ToArray());
}
}
catch { }
} /// <summary>
/// 记录出错日志
/// </summary>
/// <param name="args">第一个参数默认为错误描述</param>
public static void ErrorReflect(params string[] args)
{
try
{
StackFrame frame = new StackFrame();
MethodBase method = frame.GetMethod();
List<string> list = new List<string>();
if (method.DeclaringType != null)
{
string format = GetReflectErrorFormat(args, method.DeclaringType.ToString(), method.Name, ref list);
Logger.ErrorFormat(format, list.ToArray());
}
}
catch { }
} public static void DebugReflect(params string[] args)
{
try
{
StackFrame frame = new StackFrame();
MethodBase method = frame.GetMethod();
StackFrame frame2 = new StackFrame();
MethodBase method2 = frame2.GetMethod();
List<string> list = new List<string>();
if (method.DeclaringType != null)
{
string format = GetReflectLogFormat(args, method.DeclaringType.ToString(),
method2.Name + "/" + method.Name, ref list);
Logger.DebugFormat(format, list.ToArray());
}
}
catch { }
} public static void FatalReflect(params string[] args)
{
try
{
StackFrame frame = new StackFrame();
MethodBase method = frame.GetMethod();
List<string> list = new List<string>();
if (method.DeclaringType != null)
{
string format = GetReflectLogFormat(args, method.DeclaringType.ToString(), method.Name, ref list);
Logger.FatalFormat(format, list.ToArray());
}
}
catch { }
} public static void InfoReflect(params string[] args)
{
try
{
StackFrame frame = new StackFrame();
MethodBase method = frame.GetMethod();
StackFrame frame2 = new StackFrame();
MethodBase method2 = frame2.GetMethod();
List<string> list = new List<string>();
if (method.DeclaringType != null)
{
string format = GetReflectLogFormat(args, method.DeclaringType.ToString(),
method2.Name + "/" + method.Name, ref list);
Logger.InfoFormat(format, list.ToArray());
}
}
catch { }
} /// <summary>
/// 获取错误日志的模板
/// </summary>
/// <param name="parms"></param>
/// <param name="classname"></param>
/// <param name="methodname"></param>
/// <param name="argelist"></param>
/// <returns></returns>
/// <summary>
private static string GetReflectErrorFormat(string[] parms, string classname, string methodname, ref List<string> argelist)
{
argelist.Add(classname);
argelist.Add(methodname);
StringBuilder sb = new StringBuilder("方法:{0}.{1}\r\n");
int l = parms.Length;
if (l > )
{
sb.Append("错误:{2}\r\n");
argelist.Add(parms[]);
if (l > )
{
sb.Append("参数:");
for (int i = ; i < l; i++)
{
sb.Append("[{" + (i + ) + "}],");
argelist.Add(parms[i]);
}
}
}
return sb.ToString().TrimEnd(',');
} /// <summary>
/// 获取调试信息的模板
/// </summary>
/// <param name="parms"></param>
/// <param name="classname"></param>
/// <param name="methodname"></param>
/// <param name="argelist"></param>
/// <returns></returns>
private static string GetReflectLogFormat(string[] parms, string classname, string methodname, ref List<string> argelist)
{
argelist.Add(classname);
argelist.Add(methodname);
StringBuilder sb = new StringBuilder("方法:{0}.{1}\r\n");
int l = parms.Length;
if (l > )
{
sb.AppendFormat("参数:");
for (int i = ; i < l; i++)
{
sb.Append("[{" + (i + ) + "}],");
argelist.Add(parms[i]);
}
}
return sb.ToString().TrimEnd(',');
}
#endregion } public class Log4NetPathPattern : log4net.Util.PatternConverter
{
protected override void Convert(System.IO.TextWriter writer, object state)
{
try
{
var dirstr = System.Configuration.ConfigurationManager.AppSettings["log4net:root"];
if (string.IsNullOrWhiteSpace(dirstr)) dirstr = "logs";
dirstr = dirstr.TrimStart('/', '\\', '~');
if (!Path.IsPathRooted(dirstr)) dirstr = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, dirstr);
writer.Write(dirstr);
//如果在本项目中用,可以把文件夹加上程序集名:Assembly.GetExecutingAssembly()
//否则只有在配置文件中加项目名了
}
catch
{
//出错则默认当前目录logs文件夹
writer.Write(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs"));
} }
}
}
四、在web.config的<configSections>内部添加
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
五、在web.config的</configSections>的后面添加
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net">
<arg key="configType" value="FILE-WATCH" />
<!-- FILE,FILE-WATCH,INLINE,EXTERNAL-->
<arg key="configFile" value="~/log4net.config" />
<arg key="level" value="ALL" />
</factoryAdapter>
</logging>
</common>
六、创建测试类Class1进行调用所有类结构如下图
log4net简单用法的更多相关文章
- CATransition(os开发之画面切换) 的简单用法
CATransition 的简单用法 //引进CATransition 时要添加包“QuartzCore.framework”,然后引进“#import <QuartzCore/QuartzCo ...
- jquery.validate.js 表单验证简单用法
引入jquery.validate.js插件以及Jquery,在最后加上这个插件的方法名来引用.$('form').validate(); <!DOCTYPE html PUBLIC " ...
- NSCharacterSet 简单用法
NSCharacterSet 简单用法 NSCharacterSet其实是许多字符或者数字或者符号的组合,在网络处理的时候会用到 NSMutableCharacterSet *base = [NSMu ...
- [转]Valgrind简单用法
[转]Valgrind简单用法 http://www.cnblogs.com/sunyubo/archive/2010/05/05/2282170.html Valgrind的主要作者Julian S ...
- Oracle的substr函数简单用法
substr(字符串,截取开始位置,截取长度) //返回截取的字 substr('Hello World',0,1) //返回结果为 'H' *从字符串第一个字符开始截取长度为1的字符串 subst ...
- Ext.Net学习笔记19:Ext.Net FormPanel 简单用法
Ext.Net学习笔记19:Ext.Net FormPanel 简单用法 FormPanel是一个常用的控件,Ext.Net中的FormPanel控件同样具有非常丰富的功能,在接下来的笔记中我们将一起 ...
- TransactionScope简单用法
记录TransactionScope简单用法,示例如下: void Test() { using (TransactionScope scope = new TransactionScope()) { ...
- WPF之Treeview控件简单用法
TreeView:表示显示在树结构中分层数据具有项目可展开和折叠的控件 TreeView 的内容是可以包含丰富内容的 TreeViewItem 控件,如 Button 和 Image 控件.TreeV ...
- listActivity和ExpandableListActivity的简单用法
http://www.cnblogs.com/limingblogs/archive/2011/10/09/2204866.html 今天自己简单的总结了listActivity和Expandable ...
随机推荐
- pureftpd的搭建
1,安装purefptd软件 ftp(file transfer protocol) 文件传输协议 cd /usr/local/src wget https://download.pureftpd ...
- CodeSmith 模版
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Src="" Inherits= ...
- oracle 如何搜索当前用户下所有表里含某个值的字段?(转)
oracle 如何搜索当前用户下所有表里含某个值的字段? create or replace procedure MY_Pro_SearchKeyWord is v_sql VARCHAR2(400 ...
- python基础教程第5章——条件循环和其他语句
1.语句块是在条件为真(条件语句)时执行或者执行多次(循环语句)的一组语句.在代码前放置空格来缩进语句即可穿件语句块.块中的每行都应该缩进同样的量.在Phyton中冒号(:)用来标识语句块的开始,块中 ...
- SQL Server 控制锁升级
背景知识: 锁升级的路线图.行--> 页 --> 区(extent)-->区(表分区)--> 表: alter table 控制锁的升级行为: 1.table SQL Serv ...
- QNDTU外壳及开发板
昨天从淘宝上淘来了个DTU外壳,翻出来之前的STM32开发板和GPRS模块开发板,今天准备复习一下开发板,把裸板跑起来. 晒一下装备: 两块开发板: 51n ...
- mobile端
1.技术解决方案--------->(widget/event/ajax)->function->data------>XMLHttpRequest----->Serve ...
- STL set 使用小结
这是微软帮助文档中对集合(set)的解释: “描述了一个控制变长元素序列的对象(注:set中的key和value是Key类型的,而map中的key和value是一个pair结构中的两个分 量)的模板类 ...
- Tip.It诞生记
灵光一闪 之所以想做 Tip.It,完全是受自己初到北京时找房子各种痛苦的启发,当时为了跳过中介租房子,去58同城,豆瓣等各种网站去看房子,比如说下图就是一个典型的58同城的租房页面. 可以看到电话号 ...
- C语言当中的作用域
在C语言当中,变量的作用域分为两种:全局变量和局部变量. 在所有函数之外声明的变量是全局变量,这些变量可以在整个程序当中被访问: 局部变量是在某一对大括号({})之间生命的变量,这些变量在这对大括号之 ...