• log4net的使用


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

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

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

    写入数据库的配置:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
      </configSections>
      <log4net>
        <root>
          <level value="ALL"/>
        </root>
        <logger name="dblog" additivity="false">
          <level value="ALL"/>
          <appender-ref ref="SqlServerAppender" />
        </logger>
        <!--Oracle数据库-->
        <appender name="OracleAppender" type="log4net.Appender.AdoNetAppender">
          <!-- Oracle数据源-->
          <connectionType value="Oracle.ManagedDataAccess.Client.OracleConnection, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
          <!-- Oracle连接字符串-->
          <connectionString value="DATA SOURCE=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.3.206)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=orcl)));PASSWORD=watdb;PERSIST SECURITY INFO=True;USER ID=watdb;"/>
          <commandText value="INSERT INTO SYS_LOG(Dates,Levels,Logger,Message,Exception,ClientUser,ClientIP,RequestUrl,Action)VALUES(:Dates,:Levels,:Logger,:Message,:Exception,:ClientUser,:ClientIP,:RequestUrl,:Action)"/>
          <!--  
                 设置缓存区大小  
                 1表明有一条日志就要写入  
                 如果10就表示日志到达10条时一起写入  
                 -->
          <bufferSize value="0"/>
          <parameter>
            <parameterName value=":Dates" />
            <dbType value="DateTime" />
            <layout type="log4net.Layout.RawTimeStampLayout"/>
          </parameter>
          <parameter>
            <parameterName value=":Levels" />
            <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="200" />
            <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="4000" />
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%exception" />
            </layout>
          </parameter>
          <!--DIY-->
          <parameter>
            <parameterName value=":ClientUser" />
            <dbType value="String" />
            <size value="100" />
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%property{ClientUser}" />
            </layout>
          </parameter>
          <parameter>
            <parameterName value=":ClientIP" />
            <dbType value="String" />
            <size value="20" />
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%property{ClientIP}" />
            </layout>
          </parameter>
          <parameter>
            <parameterName value=":RequestUrl" />
            <dbType value="String" />
            <size value="500" />
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%property{RequestUrl}" />
            </layout>
          </parameter>
          <parameter>
            <parameterName value=":Action" />
            <dbType value="String" />
            <size value="20" />
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%property{Action}" />
            </layout>
          </parameter>
        </appender>
        <!--Sqlite数据库-->
        <appender name="SqliteAppender" type="log4net.Appender.AdoNetAppender">
          <bufferSize value="0" />
          <connectionType value="System.Data.SQLite.SQLiteConnection, System.Data.SQLite, Version=1.0.98.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
          <connectionString value="Data Source=|DataDirectory|test.db;Version=3;" />
          <commandText value="INSERT INTO Log (Date, Level, Logger, ClientUser,ClientIP, RequestUrl,Action, Message, Exception) VALUES (@Date, @Level, @Logger,@ClientUser,@ClientIP, @RequestUrl,@Action, @Message, @Exception)" />
          <parameter>
            <parameterName value="@Date" />
            <dbType value="DateTime" />
            <layout type="log4net.Layout.RawTimeStampLayout" />
          </parameter>
          <parameter>
            <parameterName value="@Level" />
            <dbType value="String" />
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%level" />
            </layout>
          </parameter>
          <parameter>
            <parameterName value="@Logger" />
            <dbType value="String" />
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%logger" />
            </layout>
          </parameter>
          <parameter>
            <parameterName value="@ClientUser" />
            <dbType value="String" />
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%property{ClientUser}" />
            </layout>
          </parameter>
          <parameter>
            <parameterName value="@ClientIP" />
            <dbType value="String" />
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%property{ClientIP}" />
            </layout>
          </parameter>
          <parameter>
            <parameterName value="@RequestUrl" />
            <dbType value="String" />
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%property{RequestUrl}" />
            </layout>
          </parameter>
          <parameter>
            <parameterName value="@Action" />
            <dbType value="String" />
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%property{Action}" />
            </layout>
          </parameter>
          <parameter>
            <parameterName value="@Message" />
            <dbType value="String" />
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%message" />
            </layout>
          </parameter>
          <parameter>
            <parameterName value="@Exception" />
            <dbType value="String" />
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%exception" />
            </layout>
          </parameter>
        </appender>
        <!--SqlServer数据库-->
        <appender name="SqlServerAppender" type="log4net.Appender.AdoNetAppender">
          <!-- SqlServer数据源-->
          <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
          <!-- SqlServer连接字符串-->
          <connectionString value="data source=.;initial catalog=wkmvc_db;integrated security=false;persist security info=True;User ID=sa;Password=123456;" />
          <commandText value="INSERT INTO [dbo].[SYS_LOG]([DATES],[LEVELS],[LOGGER],[CLIENTUSER],[CLIENTIP],[REQUESTURL],[ACTION],[MESSAGE],[EXCEPTION])VALUES           (@DATES,@LEVELS,@LOGGER,@CLIENTUSER,@CLIENTIP,@REQUESTURL,@ACTION,@MESSAGE,@EXCEPTION)"/>
          <!--  
                 设置缓存区大小  
                 1表明有一条日志就要写入  
                 如果10就表示日志到达10条时一起写入  
                 -->
          <bufferSize value="1"/>
          <parameter>
            <parameterName value="@DATES" />
            <dbType value="DateTime" />
            <layout type="log4net.Layout.RawTimeStampLayout" />
          </parameter>
          <parameter>
            <parameterName value="@LEVELS" />
            <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="@CLIENTUSER" />
            <dbType value="String" />
            <size value="100" />
            <layout type="log4net.Layout.PatternLayout" >
              <param name="ConversionPattern" value="%property{ClientUser}"/>
            </layout>
          </parameter>
          <parameter>
            <parameterName value="@CLIENTIP" />
            <dbType value="String" />
            <size value="100" />
            <layout type="log4net.Layout.PatternLayout" >
              <param name="ConversionPattern" value="%property{ClientIP}"/>
            </layout>
          </parameter>
          <parameter>
            <parameterName value="@REQUESTURL" />
            <dbType value="String" />
            <size value="500" />
            <layout type="log4net.Layout.PatternLayout" >
              <param name="ConversionPattern" value="%property{RequestUrl}"/>
            </layout>
          </parameter>
          <parameter>
            <parameterName value="@ACTION" />
            <dbType value="String" />
            <size value="100" />
            <layout type="log4net.Layout.PatternLayout" >
              <param name="ConversionPattern" value="%property{Action}"/>
            </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>
        </appender>
        <!--记录到文件-->
        <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net">
          <param name="File" value="datalog" />
          <param name="AppendToFile" value="true" />
          <param name="RollingStyle" value="Date" />
          <param name="DatePattern" value="\yyyy\MM-dd-HH\&quot;SQL_&quot;yyyy-MM-dd&quot;.log&quot;" />
          <param name="StaticLogFileName" value="false" />
          <layout type="log4net.Layout.PatternLayout,log4net">
            <param name="ConversionPattern" value="%d - %m%n" />
            <param name="Header" value="&#xD;&#xA;----------------------begin--------------------------&#xD;&#xA;" />
            <param name="Footer" value="&#xD;&#xA;----------------------end--------------------------&#xD;&#xA;" />
          </layout>
        </appender>
      </log4net>
      <!--必须指定框架,否则不执行,新版本默认支持4.0,可修改源文件,项目属性设定为.NET FRAMEWORK2.0后,打开重新编译,去掉其中的.NET 4.0编译导致错误环节,如此只能使用在.net 2.0框架-->
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
      </startup>
    </configuration>
    <!--
       调用实例
       log4net.ILog log = log4net.LogManager.GetLogger("Filelog");
       log.Info(Message);
       
        %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:输出语句所在的文件名
    
        %-数字:表示该项的最小长度,如果不够,则用空格填充
    
        例如,转换模式为%r [%t]%-5p %c - %m%n 的 PatternLayout 将生成类似于以下内容的输出:
    
        176 [main] INFO  org.foo.Bar - Located nearest gas station.
        -->
    View Code

    写入文件的配置:

    <?xml version="1.0" encoding="UTF-8"?>
    <log4net debug="false">
    
      <logger name="dblog">
        <level value="INFO"/>
        <appender-ref ref="LogFileAppenderByDate" />
      </logger>
    
      <!--按日期分割日志文件 一天一个-->
      <appender name="LogFileAppenderByDate" type="log4net.Appender.RollingFileAppender" >
        <!--是否续写-->
        <param name="AppendToFile" value="true" />
        <!--最小锁定模型以允许多个进程可以写入同一个文件-->
        <param name="LockingModel" value="log4net.Appender.FileAppender.MinimalLock" />
        <param name="StaticLogFileName" value="true" />
        <!--保存路径-->
        <param name="File" value="c:Log\EduBox\" />
        <param name="DatePattern" value="yyyy-MM-dd.LOG" />
        <param name="StaticLogFileName" value="false" />
        <param name="RollingStyle" value="Date" />
        <layout type="log4net.Layout.PatternLayout">
          <param name="ConversionPattern" value="--------------------------------------------------%n时间:%d %n级别:%level %n类名:%c%n文件:%F 第%L行%n日志内容:%m" />
        </layout>
      </appender>
    
      <!--按日志容量分割日志文件 10KB一个-->
      <appender name="LogFileAppenderBySize" type="log4net.Appender.RollingFileAppender" >
        <!--是否续写-->
        <param name="AppendToFile" value="true" />
        <!--最小锁定模型以允许多个进程可以写入同一个文件-->
        <param name="LockingModel" value="log4net.Appender.FileAppender.MinimalLock" />
    
        <param name="StaticLogFileName" value="true" />
    
        <!--按照文件的大小进行变换日志文件-->
        <param name="RollingStyle" value="Size" />
        <param name="File" value="log.txt" />
        <!--单个文件最大数量 好像只有在 按Size分割时有效-->
        <param name="MaximumFileSize" value="200KB"/>
        <!--保留的log文件数量 超过此数量后 自动删除之前的   好像只有在 按Size分割时有效-->
        <param name="MaxSizeRollBackups" value="2" />
    
        <param name="StaticLogFileName" value="false" />
        <layout type="log4net.Layout.PatternLayout">
          <param name="ConversionPattern" value="--------------------------------------------------%n时间:%d %n级别:%level %n类名:%c%n文件:%F 第%L行%n日志内容:%m" />
        </layout>
      </appender>
    </log4net>
    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
        {
            /// <summary>
            /// The fully qualified name of this declaring type not the type of any subclass.
            /// </summary>
            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
    
            /// <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 ExtLogManager() { }
    
            #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 IExtLog 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 IExtLog 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 IExtLog 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 IExtLog[] 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 IExtLog[] 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 IExtLog[] 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 IExtLog 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 IExtLog 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 IExtLog 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 IExtLog 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 IExtLog 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 IExtLog 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 IExtLog WrapLogger(ILogger logger)
            {
                return (IExtLog)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 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;
            }
    
            /// <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 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
Copyright © 2020-2023  润新知