博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
log4net的使用
阅读量:4582 次
发布时间:2019-06-09

本文共 19920 字,大约阅读时间需要 66 分钟。

第一步:NuGet安装Log4net,配置Web.config:

<configSections>

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>

第二步:新建Log4Net.config的配置文件,并在其中添加下面的配置信息:

写入数据库的配置:

View Code

写入文件的配置:

View Code

第三步:在Global.asax文件中的Application_Start事件中添加如下代码:

protected void Application_Start()

{

//......

//日志
log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Server.MapPath("~/log4net.config")));
}

第四步:调用log4net写日志

public log4net.Ext.IExtLog log = log4net.Ext.ExtLogManager.GetLogger("dblog");

log.Warn(Utils.GetIP(), item.ACCOUNT, Request.Url.ToString(), "Login", "系统登录,登录结果:" + json.Msg);

log.Info(Utils.GetIP(), item.ACCOUNT, Request.Url.ToString(), "Login", "系统登录,登录结果:" + json.Msg);

log.Error(Utils.GetIP(), item.ACCOUNT, Request.Url.ToString(), "Login", "系统登录,登录结果:" + json.Msg);

 

封装好的辅助类:

ExtLogImpl

using System;using System.Collections.Generic;using System.Linq;using System.Text;using log4net.Core;namespace log4net.Ext{    public class ExtLogImpl : LogImpl, IExtLog    {        ///         /// The fully qualified name of this declaring type not the type of any subclass.        ///         private readonly static Type ThisDeclaringType = typeof(ExtLogImpl);        public ExtLogImpl(ILogger logger)            : base(logger)        {        }        #region IExtLog 成员        public void Info(string clientIP, string clientUser, string requestUri, string action, object message)        {            Info(clientIP, clientUser, requestUri, action, message, null);        }        public void Info(string clientIP, string clientUser, string requestUri, string action, object message, Exception t)        {            if (this.IsInfoEnabled)            {                LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Info, message, t);                loggingEvent.Properties["ClientIP"] = clientIP;                loggingEvent.Properties["ClientUser"] = clientUser;                loggingEvent.Properties["RequestUrl"] = requestUri;                loggingEvent.Properties["Action"] = action;                Logger.Log(loggingEvent);            }        }        public void Warn(string clientIP, string clientUser, string requestUri, string action, object message)        {            Warn(clientIP, clientUser, requestUri, action, message, null);        }        public void Warn(string clientIP, string clientUser, string requestUri, string action, object message, Exception t)        {            if (this.IsWarnEnabled)            {                LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Warn, message, t);                loggingEvent.Properties["ClientIP"] = clientIP;                loggingEvent.Properties["ClientUser"] = clientUser;                loggingEvent.Properties["RequestUrl"] = requestUri;                loggingEvent.Properties["Action"] = action;                Logger.Log(loggingEvent);            }        }        public void Error(string clientIP, string clientUser, string requestUri, string action, object message)        {            Error(clientIP, clientUser, requestUri, action, message, null);        }        public void Error(string clientIP, string clientUser, string requestUri, string action, object message, Exception t)        {            if (this.IsErrorEnabled)            {                LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Error, message, t);                loggingEvent.Properties["ClientIP"] = clientIP;                loggingEvent.Properties["ClientUser"] = clientUser;                loggingEvent.Properties["RequestUrl"] = requestUri;                loggingEvent.Properties["Action"] = action;                Logger.Log(loggingEvent);            }        }        public void Fatal(string clientIP, string clientUser, string requestUri, string action, object message)        {            Fatal(clientIP, clientUser, requestUri, action, message, null);        }        public void Fatal(string clientIP, string clientUser, string requestUri, string action, object message, Exception t)        {            if (this.IsFatalEnabled)            {                LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Fatal, message, t);                loggingEvent.Properties["ClientIP"] = clientIP;                loggingEvent.Properties["ClientUser"] = clientUser;                loggingEvent.Properties["RequestUrl"] = requestUri;                loggingEvent.Properties["Action"] = action;                Logger.Log(loggingEvent);            }        }        #endregion    }}
View Code

ExtLogManager

using log4net.Core;using System;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Text;namespace log4net.Ext{    public class ExtLogManager    {        #region Static Member Variables        ///         /// The wrapper map to use to hold the 
objects ///
private static readonly WrapperMap s_wrapperMap = new WrapperMap(new WrapperCreationHandler(WrapperCreationHandler)); #endregion #region Constructor /// /// Private constructor to prevent object creation /// private ExtLogManager() { } #endregion #region Type Specific Manager Methods /// /// Returns the named logger if it exists /// ///
///
If the named logger exists (in the default hierarchy) then it /// returns a reference to the logger, otherwise it returns ///
null
.
///
/// The fully qualified logger name to look for ///
The logger found, or null
public static IExtLog Exists(string name) { return Exists(Assembly.GetCallingAssembly(), name); } /// /// Returns the named logger if it exists /// ///
///
If the named logger exists (in the specified domain) then it /// returns a reference to the logger, otherwise it returns ///
null
.
///
/// the domain to lookup in /// The fully qualified logger name to look for ///
The logger found, or null
public static IExtLog Exists(string domain, string name) { return WrapLogger(LoggerManager.Exists(domain, name)); } /// /// Returns the named logger if it exists /// ///
///
If the named logger exists (in the specified assembly's domain) then it /// returns a reference to the logger, otherwise it returns ///
null
.
///
/// the assembly to use to lookup the domain /// The fully qualified logger name to look for ///
The logger found, or null
public static IExtLog Exists(Assembly assembly, string name) { return WrapLogger(LoggerManager.Exists(assembly, name)); } /// /// Returns all the currently defined loggers in the default domain. /// ///
///
The root logger is
not included in the returned array.
///
///
All the defined loggers
public static IExtLog[] GetCurrentLoggers() { return GetCurrentLoggers(Assembly.GetCallingAssembly()); } /// /// Returns all the currently defined loggers in the specified domain. /// /// the domain to lookup in ///
/// The root logger is
not included in the returned array. ///
///
All the defined loggers
public static IExtLog[] GetCurrentLoggers(string domain) { return WrapLoggers(LoggerManager.GetCurrentLoggers(domain)); } /// /// Returns all the currently defined loggers in the specified assembly's domain. /// /// the assembly to use to lookup the domain ///
/// The root logger is
not included in the returned array. ///
///
All the defined loggers
public static IExtLog[] GetCurrentLoggers(Assembly assembly) { return WrapLoggers(LoggerManager.GetCurrentLoggers(assembly)); } /// /// Retrieve or create a named logger. /// ///
///
Retrieve a logger named as the
/// parameter. If the named logger already exists, then the /// existing instance will be returned. Otherwise, a new instance is /// created.
/// ///
By default, loggers do not have a set level but inherit /// it from the hierarchy. This is one of the central features of /// log4net.
///
/// The name of the logger to retrieve. ///
the logger with the name specified
public static IExtLog GetLogger(string name) { return GetLogger(Assembly.GetCallingAssembly(), name); } /// /// Retrieve or create a named logger. /// ///
///
Retrieve a logger named as the
/// parameter. If the named logger already exists, then the /// existing instance will be returned. Otherwise, a new instance is /// created.
/// ///
By default, loggers do not have a set level but inherit /// it from the hierarchy. This is one of the central features of /// log4net.
///
/// the domain to lookup in /// The name of the logger to retrieve. ///
the logger with the name specified
public static IExtLog GetLogger(string domain, string name) { return WrapLogger(LoggerManager.GetLogger(domain, name)); } /// /// Retrieve or create a named logger. /// ///
///
Retrieve a logger named as the
/// parameter. If the named logger already exists, then the /// existing instance will be returned. Otherwise, a new instance is /// created.
/// ///
By default, loggers do not have a set level but inherit /// it from the hierarchy. This is one of the central features of /// log4net.
///
/// the assembly to use to lookup the domain /// The name of the logger to retrieve. ///
the logger with the name specified
public static IExtLog GetLogger(Assembly assembly, string name) { return WrapLogger(LoggerManager.GetLogger(assembly, name)); } /// /// Shorthand for
. ///
///
/// Get the logger for the fully qualified name of the type specified. ///
/// The full name of
will /// be used as the name of the logger to retrieve. ///
the logger with the name specified
public static IExtLog GetLogger(Type type) { return GetLogger(Assembly.GetCallingAssembly(), type.FullName); } /// /// Shorthand for
. ///
///
/// Get the logger for the fully qualified name of the type specified. ///
/// the domain to lookup in /// The full name of
will /// be used as the name of the logger to retrieve. ///
the logger with the name specified
public static IExtLog GetLogger(string domain, Type type) { return WrapLogger(LoggerManager.GetLogger(domain, type)); } /// /// Shorthand for
. ///
///
/// Get the logger for the fully qualified name of the type specified. ///
/// the assembly to use to lookup the domain /// The full name of
will /// be used as the name of the logger to retrieve. ///
the logger with the name specified
public static IExtLog GetLogger(Assembly assembly, Type type) { return WrapLogger(LoggerManager.GetLogger(assembly, type)); } #endregion #region Extension Handlers /// /// Lookup the wrapper object for the logger specified /// /// the logger to get the wrapper for ///
the wrapper for the logger specified
private static IExtLog WrapLogger(ILogger logger) { return (IExtLog)s_wrapperMap.GetWrapper(logger); } /// /// Lookup the wrapper objects for the loggers specified /// /// the loggers to get the wrappers for ///
Lookup the wrapper objects for the loggers specified
private static IExtLog[] WrapLoggers(ILogger[] loggers) { IExtLog[] results = new IExtLog[loggers.Length]; for (int i = 0; i < loggers.Length; i++) { results[i] = WrapLogger(loggers[i]); } return results; } /// /// Method to create the
objects used by /// this manager. ///
/// The logger to wrap ///
The wrapper for the logger specified
private static ILoggerWrapper WrapperCreationHandler(ILogger logger) { return new ExtLogImpl(logger); } #endregion }}
View Code

IExtLog

using System;using System.Collections.Generic;using System.Linq;using System.Text;using log4net;namespace log4net.Ext{    public interface IExtLog : ILog    {        void Info(string clientIP, string clientUser, string requestUri, string action, object message);        void Info(string clientIP, string clientUser, string requestUri, string action, object message, Exception t);        void Warn(string clientIP, string clientUser, string requestUri, string action, object message);        void Warn(string clientIP, string clientUser, string requestUri, string action, object message, Exception t);        void Error(string clientIP, string clientUser, string requestUri, string action, object message);        void Error(string clientIP, string clientUser, string requestUri, string action, object message, Exception t);        void Fatal(string clientIP, string clientUser, string requestUri, string action, object message);        void Fatal(string clientIP, string clientUser, string requestUri, string action, object message, Exception t);    }}
View Code

 参考:

http://www.cnblogs.com/huanghai223/archive/2012/02/21/2361529.html

http://www.cnblogs.com/jiajinyi/p/5884930.html

转载于:https://www.cnblogs.com/xsj1989/p/6085375.html

你可能感兴趣的文章
第七章学习小结
查看>>
GS LiveMgr心跳管理类
查看>>
设计模式学习笔记(二)之观察者模式、装饰者模式
查看>>
mysql导出数据库和恢复数据库代码
查看>>
走出软件泥潭 第一回 雪上加霜
查看>>
小鸟哥哥博客 For SAE
查看>>
gui编程实践(3)--记事本界面 JMenuBar JMenu
查看>>
App测试方法总结
查看>>
51nod-1228: 序列求和
查看>>
BZOJ1303: [CQOI2009]中位数图
查看>>
2015上海马拉松线上跑感悟-人生如同一场马拉松
查看>>
北航软院2013级C#期末考试部分考题解答
查看>>
CentOS 系统中安装 ArcGIS Server10.1 一些问题及解决
查看>>
Sharepoint学习笔记—习题系列--70-573习题解析 -(Q142-Q143)
查看>>
asp.net里登陆记住密码
查看>>
【BZOJ】2190 [SDOI2008]仪仗队(欧拉函数)
查看>>
线性规划中的单纯形法与内点法(原理、步骤以及matlab实现)(一)
查看>>
简单DP【p2758】编辑距离
查看>>
Spring Data JPA:关联映射操作
查看>>
JWT入门简介
查看>>