log4Net配置以及使用入门

2018-06-22 07:26:09来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

 

<configSections>
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
    <!--<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />-->
  </configSections>
  <log4net>
    <!--定义输出到文件中-->
    <!--Error-->
    <appender name="RollingErrorLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <!--定义文件存放位置-->
      <file  value="Mylog\\ERROR\\" />
      <appendToFile value="true"/>
      <rollingStyle value="Date"/>
      <datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.txt'"/>
      <staticLogFileName value="false"/>
      <param name="MaxSizeRollBackups" value="1000"/>
      <layout type="log4net.Layout.PatternLayout">
        <!--输出格式-->
        <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别:%-5level %n出错类:%logger property: [%property{NDC}] - %n错误描述:%message%newline"/>
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <!--将日志过滤,只记录ERROR到FATAL-->
        <levelMin value="ERROR" />
        <levelMax value="ERROR" />
      </filter>
    </appender>
    <!--FATAL-->
    <appender name="RollingFATALLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <!--定义文件存放位置-->
      <file  value="Mylog\\FATAL\\" />
      <appendToFile value="true"/>
      <rollingStyle value="Date"/>
      <datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.txt'"/>
      <staticLogFileName value="false"/>
      <param name="MaxSizeRollBackups" value="1000"/>
      <layout type="log4net.Layout.PatternLayout">
        <!--输出格式-->
        <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别:%-5level %n出错类:%logger property: [%property{NDC}] - %n错误描述:%message%newline"/>
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <!--将日志过滤,只记录ERROR到FATAL-->
        <levelMin value="FATAL" />
        <levelMax value="FATAL" />
      </filter>
    </appender>
    <!--定义输出到数据库-->
    <!-- 
    在SQL Server中创建表的SQL语句 
    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 
); 
    -->
    <appender name="AdoNetAppenderErrorSQLServer" 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="server=LONGPENG;uid=sa;pwd=0129;database=LogDB;" />
      <commandText value="INSERT INTO LogError ([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>
    </appender>
    <root>
      <level value="ALL" />
      <!--文件形式记录日志-->
      <appender-ref ref="RollingErrorLogFileAppender"/>
      <appender-ref ref="RollingFATALLogFileAppender"/>

 <!--数据库形式记录日志-->
      <appender-ref ref="AdoNetAppenderErrorSQLServer"/>
    </root>
  </log4net>

=========================另一种使用的配置==============================

<log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="SysAppender" />
      <appender-ref ref="consoleApp" />
    </root>
    <!--<logger name="WebLogger">
      <level value="DEBUG" />
    </logger>-->
    <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net">
      <!--<param name="File" value="E:\\COLDDEMO\\项目\\实战\\Solution201708\\logs\\" />-->
      <param name="File" value="..\\..\\MyLog\\AT\\ERROR\\" />
      <!--<param name="File" value="C:\\TestWeb\\Debug\\Error\\" />-->
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="&quot;&quot;yyyyMMdd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value=" ------------------------------------------------&#xD;&#xA;" />
        <param name="Footer" value=" ----------------------footer--------------------------&#xD;&#xA;" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <!--将日志过滤,只记录ERROR到FATAL-->
        <levelMin value="ERROR" />
        <levelMax value="ERROR" />
      </filter>
    </appender>
    <!--..\\..\\MyLog\\AT\\-->
    <appender name="consoleApp" type="log4net.Appender.RollingFileAppender,log4net">
      <!--<param name="File" value="E:\\COLDDEMO\\项目\\实战\\Solution201708\\logs\\" />-->
      <param name="File" value="..\\..\\MyLog\\AT\\Warn\\" />
      <!--<param name="File" value="C:\\TestWeb\\Debug\\Error\\" />-->
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="&quot;&quot;yyyyMMdd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value=" ------------------------------------------------&#xD;&#xA;" />
        <param name="Footer" value=" ----------------------footer--------------------------&#xD;&#xA;" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <!--将日志过滤,只记录Warn-->
        <levelMin value="Warn" />
        <levelMax value="Warn" />
      </filter>
    </appender>
  </log4net>

============================================================

使用:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace WebAppl
{
    public class LogHelper
    {
        /// <summary>
        /// 调用Log4net写日志
        /// </summary>
        /// <param name="logContent">日志内容</param>
        /// <param name="log4Level">记录日志等级,枚举</param>
        public static void WriteLog(string logContent, Log4NetLevel log4Level)
        {
            WriteLog(null, logContent, log4Level);
        }

        /// <summary>
        /// 调用Log4net写日志
        /// </summary>
        /// <param name="type">类的类型,指定日志中错误的具体类
        /// <param name="logContent">日志内容</param>
        /// <param name="log4Level">记录日志等级,枚举</param>
        public static void WriteLog(Type type, string logContent, Log4NetLevel log4Level)
        {
            ILog log = type == null ? LogManager.GetLogger("") : LogManager.GetLogger(type);

            switch (log4Level)
            {
                case Log4NetLevel.Warn:
                    log.Warn(logContent);
                    break;
                case Log4NetLevel.Debug:
                    log.Debug(logContent);
                    break;
                case Log4NetLevel.Info:
                    log.Info(logContent);
                    break;
                case Log4NetLevel.Fatal:
                    log.Fatal(logContent);
                    break;
                case Log4NetLevel.Error:
                    log.Error(logContent);
                    break;
            }
        }

    }


    /// <summary>
    /// log4net 日志等级类型枚举
    /// </summary>
    public enum Log4NetLevel
    {
        [Description("警告信息")]
        Warn = 1,
        [Description("调试信息")]
        Debug = 2,
        [Description("一般信息")]
        Info = 3,
        [Description("严重错误")]
        Fatal = 4,
        [Description("错误日志")]
        Error = 5
    }
}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:多线程编程学习笔记——使用并发集合(三)

下一篇:NEST - Elasticsearch 的高级客户端