Log4Net .NET log處理

1.NuGet 安裝Log4Net.web

 

2.新建一個Common的project,而且添加一個LogWriter的類:數據庫

public class LogWriter
    {
        //Error log
        public static void Error(Exception ex)
        {
            LogHelper.GetInstanse().Logger.Error(string.Format("{0} - {1}", ex.Message, ex.StackTrace));
        }
        public static void Error(string message, Exception ex)
        {
            LogHelper.GetInstanse().Logger.Error(message, ex);
        }
        //Info Log
        public static void Info(string message)
        {
            LogHelper.GetInstanse().Logger.Info(message);
        }
        public static void Info(string format, params object[] args)
        {
            LogHelper.GetInstanse().Logger.InfoFormat(format, args);
        }
        //Debug log
        public static void Debug(string message)
        {
            LogHelper.GetInstanse().Logger.Debug(message);
        }

        public static void Debug(string format, params object[] args)
        {
            LogHelper.GetInstanse().Logger.DebugFormat(format, args);
        }

    }
    class LogHelper
    {
        private static LogHelper _logHelper = null;
        private static ILog _logger = null;
        private static readonly object syncRoot = new object();
        public LogHelper()
        {
            var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + @"\App_Config\Log4Net.config");
            log4net.Config.XmlConfigurator.Configure(logCfg);
            _logger = LogManager.GetLogger(ConfigurationManager.AppSettings["LoggerName"]);
        }
        public static LogHelper GetInstanse()
        {
            if (_logHelper == null)
            {
                lock (syncRoot)
                {
                    if (_logHelper == null)
                    {
                        _logHelper = new LogHelper();
                    }
                }
            }
            return _logHelper;
        }
        public ILog Logger
        {
            get
            {
                return _logger;
            }
        }
    }

 

3.在須要使用LogWriter的project中新建App_Config文件夾,加入配置文件:app

Log4Net.configspa

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <root>
    <!--
            <level value="ALL" />
            <appender-ref ref="rootFile" />
            -->
  </root>
  <logger name="TestLog">
    <level value="ALL" />
    <appender-ref ref="DebugLoging"/>
    <appender-ref ref="InfoLoging" />
    <appender-ref ref="ErrorLoging" />
  </logger>
  <appender name="DebugLoging" type="log4net.Appender.RollingFileAppender,log4net" >
    <param name="File" value="_LogData\log_debug" />
    <param name="RollingStyle" value="Date" />
    <param name="DatePattern" value="yyyyMMdd&quot;.log&quot;" />
    <param name="AppendToFile" 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="InfoLoging" type="log4net.Appender.RollingFileAppender,log4net" >
    <param name="File" value="_LogData\log_Info" />
    <param name="RollingStyle" value="Date" />
    <param name="DatePattern" value="yyyyMMdd&quot;.log&quot;" />
    <param name="AppendToFile" 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="INFO" />
      <param name="LevelMax" value="INFO" />
    </filter>
  </appender>
  <appender name="ErrorLoging" type="log4net.Appender.RollingFileAppender,log4net" >
    <param name="File" value="_LogData\log_error" />
    <param name="RollingStyle" value="Date" />
    <param name="DatePattern" value="yyyyMMdd&quot;.log&quot;" />
    <param name="AppendToFile" 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="ADONetAppender" type="log4net.Appender.ADONetAppender">
    <bufferSize value="10" />
    <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <connectionString value="" />
    <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="100" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%t" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@log_level" />
      <dbType value="String" />
      <size value="200" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%p" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@logger" />
      <dbType value="String" />
      <size value="500" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%logger" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@message" />
      <dbType value="String" />
      <size value="3000" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%m" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@exception" />
      <dbType value="String" />
      <size value="4000" />
      <layout type="log4net.Layout.ExceptionLayout" />
    </parameter>
  </appender>
</log4net>

配置文件能夠配置log 類型,info, error debug。debug

保存路徑,保存方式(文件和數據庫,如果數據庫要填寫connectstring)3d

4.在web.config/app.config中配置log的名稱,這裏是TestLog,和上面的log 配置文件保持一致。code

<add key="LoggerName" value="TestLog" />orm

5.使用:xml

LogWriter.Error("Error occurs", e);e 是exception 對象;對象

LogWriter.Info("Test log feature.");  

 

6.在路徑_LogData下就會按照天天產生對應的log

相關文章
相關標籤/搜索