Log4Net 自定义字段

 

1. 继承ILog

public interface IWebLog : ILog
    {
        void Info(string clientIP, string requestUrl, object message);
        void Info(string clientIP, string requestUrl, object message, Exception t);

        void Warn(string clientIP, string requestUrl, object message);
        void Warn(string clientIP, string requestUrl, object message, Exception t);

        void Error(string clientIP, string requestUrl, object message);
        void Error(string clientIP, string requestUrl, object message, Exception t);

        void Fatal(string clientIP, string requestUrl, object message);
        void Fatal(string clientIP, string requestUrl, object message, Exception t);
    }

 

2.实现接口

public class WebLogImpl : LogImpl, IWebLog
    {
        /// <summary>
        /// The fully qualified name of this declaring type not the type of any subclass.
        /// </summary>
        private readonly static Type ThisDeclaringType = typeof(WebLogImpl);

        public WebLogImpl(ILogger logger)
            : base(logger)
        {
        }

        #region Implementation of IWebLog

        public void Info(string clientIP, string requestUrl, object message)
        {
            Info(clientIP, requestUrl, message, null);
        }

        public void Info(string clientIP, string requestUrl, object message, System.Exception t)
        {
            if (this.IsInfoEnabled)
            {
                LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Info, message, t);
                loggingEvent.Properties["ClientIP"] = clientIP;
                loggingEvent.Properties["RequestUrl"] = requestUrl;
                Logger.Log(loggingEvent);
            }
        }

        public void Warn(string clientIP, string requestUrl, object message)
        {
            Warn(clientIP, requestUrl, message, null);
        }

        public void Warn(string clientIP, string requestUrl, object message, System.Exception t)
        {
            if (this.IsWarnEnabled)
            {
                LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Warn, message, t);
                loggingEvent.Properties["ClientIP"] = clientIP;
                loggingEvent.Properties["RequestUrl"] = requestUrl;
                Logger.Log(loggingEvent);
            }
        }

        public void Error(string clientIP, string requestUrl, object message)
        {
            Error(clientIP, requestUrl, message, null);
        }

        public void Error(string clientIP, string requestUrl, object message, System.Exception t)
        {
            if (this.IsErrorEnabled)
            {
                LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Error, message, t);
                loggingEvent.Properties["ClientIP"] = clientIP;
                loggingEvent.Properties["RequestUrl"] = requestUrl;
                Logger.Log(loggingEvent);
            }
        }

        public void Fatal(string clientIP, string requestUrl, object message)
        {
            Fatal(clientIP, requestUrl, null);
        }

        public void Fatal(string clientIP, string requestUrl, object message, System.Exception t)
        {
            if (this.IsFatalEnabled)
            {
                LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Fatal, message, t);
                loggingEvent.Properties["ClientIP"] = clientIP;
                loggingEvent.Properties["RequestUrl"] = requestUrl;
                Logger.Log(loggingEvent);
            }
        }

        #endregion Implementation of IWebLog
    }

3.定义管理类

public class WebLogManager
    {
        #region Static Member Variables

        /// <summary>
        /// The wrapper map to use to hold the <see cref="WebLogImpl"/> objects
        /// </summary>
        private static readonly WrapperMap s_wrapperMap = new WrapperMap(new WrapperCreationHandler(WrapperCreationHandler));

        #endregion

        #region Constructor

        /// <summary>
        /// Private constructor to prevent object creation
        /// </summary>
        private WebLogManager() { }

        #endregion

        #region Type Specific Manager Methods

        /// <summary>
        /// Returns the named logger if it exists
        /// </summary>
        /// <remarks>
        /// <para>If the named logger exists (in the default hierarchy) then it
        /// returns a reference to the logger, otherwise it returns
        /// <c>null</c>.</para>
        /// </remarks>
        /// <param name="name">The fully qualified logger name to look for</param>
        /// <returns>The logger found, or null</returns>
        public static IWebLog Exists(string name)
        {
            return Exists(Assembly.GetCallingAssembly(), name);
        }

        /// <summary>
        /// Returns the named logger if it exists
        /// </summary>
        /// <remarks>
        /// <para>If the named logger exists (in the specified domain) then it
        /// returns a reference to the logger, otherwise it returns
        /// <c>null</c>.</para>
        /// </remarks>
        /// <param name="domain">the domain to lookup in</param>
        /// <param name="name">The fully qualified logger name to look for</param>
        /// <returns>The logger found, or null</returns>
        public static IWebLog Exists(string domain, string name)
        {
            return WrapLogger(LoggerManager.Exists(domain, name));
        }

        /// <summary>
        /// Returns the named logger if it exists
        /// </summary>
        /// <remarks>
        /// <para>If the named logger exists (in the specified assembly's domain) then it
        /// returns a reference to the logger, otherwise it returns
        /// <c>null</c>.</para>
        /// </remarks>
        /// <param name="assembly">the assembly to use to lookup the domain</param>
        /// <param name="name">The fully qualified logger name to look for</param>
        /// <returns>The logger found, or null</returns>
        public static IWebLog Exists(Assembly assembly, string name)
        {
            return WrapLogger(LoggerManager.Exists(assembly, name));
        }

        /// <summary>
        /// Returns all the currently defined loggers in the default domain.
        /// </summary>
        /// <remarks>
        /// <para>The root logger is <b>not</b> included in the returned array.</para>
        /// </remarks>
        /// <returns>All the defined loggers</returns>
        public static IWebLog[] GetCurrentLoggers()
        {
            return GetCurrentLoggers(Assembly.GetCallingAssembly());
        }

        /// <summary>
        /// Returns all the currently defined loggers in the specified domain.
        /// </summary>
        /// <param name="domain">the domain to lookup in</param>
        /// <remarks>
        /// The root logger is <b>not</b> included in the returned array.
        /// </remarks>
        /// <returns>All the defined loggers</returns>
        public static IWebLog[] GetCurrentLoggers(string domain)
        {
            return WrapLoggers(LoggerManager.GetCurrentLoggers(domain));
        }

        /// <summary>
        /// Returns all the currently defined loggers in the specified assembly's domain.
        /// </summary>
        /// <param name="assembly">the assembly to use to lookup the domain</param>
        /// <remarks>
        /// The root logger is <b>not</b> included in the returned array.
        /// </remarks>
        /// <returns>All the defined loggers</returns>
        public static IWebLog[] GetCurrentLoggers(Assembly assembly)
        {
            return WrapLoggers(LoggerManager.GetCurrentLoggers(assembly));
        }

        /// <summary>
        /// Retrieve or create a named logger.
        /// </summary>
        /// <remarks>
        /// <para>Retrieve a logger named as the <paramref name="name"/>
        /// parameter. If the named logger already exists, then the
        /// existing instance will be returned. Otherwise, a new instance is
        /// created.</para>
        /// 
        /// <para>By default, loggers do not have a set level but inherit
        /// it from the hierarchy. This is one of the central features of
        /// log4net.</para>
        /// </remarks>
        /// <param name="name">The name of the logger to retrieve.</param>
        /// <returns>the logger with the name specified</returns>
        public static IWebLog GetLogger(string name)
        {
            return GetLogger(Assembly.GetCallingAssembly(), name);
        }

        /// <summary>
        /// Retrieve or create a named logger.
        /// </summary>
        /// <remarks>
        /// <para>Retrieve a logger named as the <paramref name="name"/>
        /// parameter. If the named logger already exists, then the
        /// existing instance will be returned. Otherwise, a new instance is
        /// created.</para>
        /// 
        /// <para>By default, loggers do not have a set level but inherit
        /// it from the hierarchy. This is one of the central features of
        /// log4net.</para>
        /// </remarks>
        /// <param name="domain">the domain to lookup in</param>
        /// <param name="name">The name of the logger to retrieve.</param>
        /// <returns>the logger with the name specified</returns>
        public static IWebLog GetLogger(string domain, string name)
        {
            return WrapLogger(LoggerManager.GetLogger(domain, name));
        }

        /// <summary>
        /// Retrieve or create a named logger.
        /// </summary>
        /// <remarks>
        /// <para>Retrieve a logger named as the <paramref name="name"/>
        /// parameter. If the named logger already exists, then the
        /// existing instance will be returned. Otherwise, a new instance is
        /// created.</para>
        /// 
        /// <para>By default, loggers do not have a set level but inherit
        /// it from the hierarchy. This is one of the central features of
        /// log4net.</para>
        /// </remarks>
        /// <param name="assembly">the assembly to use to lookup the domain</param>
        /// <param name="name">The name of the logger to retrieve.</param>
        /// <returns>the logger with the name specified</returns>
        public static IWebLog GetLogger(Assembly assembly, string name)
        {
            return WrapLogger(LoggerManager.GetLogger(assembly, name));
        }

        /// <summary>
        /// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
        /// </summary>
        /// <remarks>
        /// Get the logger for the fully qualified name of the type specified.
        /// </remarks>
        /// <param name="type">The full name of <paramref name="type"/> will 
        /// be used as the name of the logger to retrieve.</param>
        /// <returns>the logger with the name specified</returns>
        public static IWebLog GetLogger(Type type)
        {
            return GetLogger(Assembly.GetCallingAssembly(), type.FullName);
        }

        /// <summary>
        /// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
        /// </summary>
        /// <remarks>
        /// Get the logger for the fully qualified name of the type specified.
        /// </remarks>
        /// <param name="domain">the domain to lookup in</param>
        /// <param name="type">The full name of <paramref name="type"/> will 
        /// be used as the name of the logger to retrieve.</param>
        /// <returns>the logger with the name specified</returns>
        public static IWebLog GetLogger(string domain, Type type)
        {
            return WrapLogger(LoggerManager.GetLogger(domain, type));
        }

        /// <summary>
        /// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
        /// </summary>
        /// <remarks>
        /// Get the logger for the fully qualified name of the type specified.
        /// </remarks>
        /// <param name="assembly">the assembly to use to lookup the domain</param>
        /// <param name="type">The full name of <paramref name="type"/> will 
        /// be used as the name of the logger to retrieve.</param>
        /// <returns>the logger with the name specified</returns>
        public static IWebLog GetLogger(Assembly assembly, Type type)
        {
            return WrapLogger(LoggerManager.GetLogger(assembly, type));
        }

        #endregion

        #region Extension Handlers

        /// <summary>
        /// Lookup the wrapper object for the logger specified
        /// </summary>
        /// <param name="logger">the logger to get the wrapper for</param>
        /// <returns>the wrapper for the logger specified</returns>
        private static IWebLog WrapLogger(ILogger logger)
        {
            return (IWebLog)s_wrapperMap.GetWrapper(logger);
        }

        /// <summary>
        /// Lookup the wrapper objects for the loggers specified
        /// </summary>
        /// <param name="loggers">the loggers to get the wrappers for</param>
        /// <returns>Lookup the wrapper objects for the loggers specified</returns>
        private static IWebLog[] WrapLoggers(ILogger[] loggers)
        {
            IWebLog[] results = new IWebLog[loggers.Length];
            for (int i = 0; i < loggers.Length; i++)
            {
                results[i] = WrapLogger(loggers[i]);
            }
            return results;
        }

        /// <summary>
        /// Method to create the <see cref="ILoggerWrapper"/> objects used by
        /// this manager.
        /// </summary>
        /// <param name="logger">The logger to wrap</param>
        /// <returns>The wrapper for the logger specified</returns>
        private static ILoggerWrapper WrapperCreationHandler(ILogger logger)
        {
            return new WebLogImpl(logger);
        }

        #endregion
    }

4.Web.Config

 

<configSections>
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
  </configSections>
  <system.diagnostics>
    <trace autoflush="true">
      <listeners>
        <add name="textWriterTraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="D:/log4net.txt"/>
      </listeners>
    </trace>
  </system.diagnostics>
  
  <appSettings>
    <add key="log4net.Internal.Debug" value="true"/>
  </appSettings>

<log4net>
    <!--定义输出到数据库中,这里举例输出到Access数据库中,数据库为C盘的log4net.mdb-->
    <appender name="AdoNetAppender_SQLServer" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1"/>
      <connectionType value="System.Data.SqlClient.SqlConnection"/>
      <connectionString value="Password=123456;Persist Security Info=True;User ID=sa;Initial Catalog=CmsDb;Data Source=PC-PC"/>
      <commandText value="INSERT INTO Log (Date, Level, Logger, ClientIP, RequestUrl, Message, Exception) VALUES (@Date, @Level, @Logger, @ClientIP, @RequestUrl, @Message, @Exception)"/>
      <parameter>
        <parameterName value="@Date"/>
        <dbType value="DateTime"/>
        <layout type="log4net.Layout.RawTimeStampLayout"/>
      </parameter>
      <parameter>
        <parameterName value="@Level"/>
        <dbType value="String"/>
        <size value="255" />
        <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="@ClientIP"/>
        <dbType value="String"/>
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%property{ClientIP}"/>
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@RequestUrl"/>
        <dbType value="String"/>
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%property{RequestUrl}"/>
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Message"/>
        <dbType value="String"/>
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message"/>
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Exception"/>
        <dbType value="String"/>
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%exception"/>
        </layout>
      </parameter>
    </appender>
    <!--定义日志的输出媒介,下面定义日志以四种方式输出。也可以下面的按照一种类型或其他类型输出。-->
    <root>
      <!--文件形式记录日志-->
      <!--<appender-ref ref="LogFileAppender" />-->
      <!--控制台控制显示日志-->
      <!--<appender-ref ref="ConsoleAppender" />-->
      <!--Windows事件日志-->
      <!--<appender-ref ref="EventLogAppender" />-->
      <!-- 如果不启用相应的日志记录,可以通过这种方式注释掉-->
      <appender-ref ref="AdoNetAppender_SQLServer"/>
    </root>
  </log4net>

5.Controller

 public ActionResult Index()
        {
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            //ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
            IWebLog log = WebLogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

            log.Error("192.168.10.12","http://www.baidu.com","ceshi");


            ////记录错误日志
            //log.Error("error", new Exception("发生了一个异常"));
            ////记录严重错误
            //log.Fatal("fatal", new Exception("发生了一个致命错误"));
            ////记录一般信息
            //log.Info("info");
            ////记录调试信息
            //log.Debug("debug");
            ////记录警告信息
            //log.Warn("warn");


            stopwatch.Stop();
            long a = stopwatch.ElapsedTicks;
            ViewBag.tt = a;
            return View();
        }

6.AssemblyInfo.cs

在项目的 AssemblyInfo.cs文件中,增加 

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

或者在Globle.asax 中增加

log4net.Config.XmlConfigurator.Configure();  

 

Demo文件 下载

 

posted on 2016-02-20 21:39  忙碌ing  阅读(322)  评论(0)    收藏  举报

导航