1. 程式人生 > >關於log4net日誌寫入mysql數據庫記錄

關於log4net日誌寫入mysql數據庫記錄

分別是 values backup 地方 logs com ase layout orm

網上關於log4net日誌寫入mysql數據庫的博客感覺比較少,所以這邊搞定之後先過來記錄一下。

首先新建個項目,我命名是log4netDemo,然後需要引入兩個dll,一個是mysql.dll,一個是log4net.dll。可以通過NuGet安裝這兩個dll,如下圖

技術分享圖片

技術分享圖片

我這邊mysql和log4net的版本分別是6.10.8和2.0.8,當然mysql更高版本的也是可以的。

然後在項目中新建一個log4net.config的配置文件,配置全文如下:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <
compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <appender
name="AdoNetAppender_MySql" type="log4net.Appender.AdoNetAppender"> <bufferSize value="1" /> <param name="ConnectionType" value="MySql.Data.MySqlClient.MySqlConnection, MySql.Data"/> <param name="ConnectionString" value="server=localhost;database=test_log4net;Uid=root;Pwd=123456;port=3306;"
/> <commandText value="INSERT INTO loggermall (`log_thread`,`log_level`,`log_logger`,`log_message`) VALUES (@log_thread,@log_level,@log_logger,@log_message)" /> <parameter> <parameterName value="@log_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="%-5level"/> </layout> </parameter> <parameter> <parameterName value="@log_logger"/> <dbType value="String"/> <size value="50"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger"/> </layout> </parameter> <parameter> <parameterName value="@log_message"/> <dbType value="String"/> <size value="4000"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message"/> </layout> </parameter> </appender> <!--錯誤日誌--> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="log\\LogError\\"/> <appendToFile value="true"/> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <rollingStyle value="Date"/> <datePattern value="yyyy\\yyyyMM\\yyyyMMdd‘.txt‘"/> <staticLogFileName value="false"/> <param name="MaxSizeRollBackups" value="100"/> <layout type="log4net.Layout.PatternLayout"> <!--每條日誌末尾的文字說明--> <!--輸出格式--> <!--樣例:2008-03-26 13:42:32,111 [10] INFO Log4NetDemo.MainClass [(null)] - info--> <conversionPattern value="%newline %n記錄時間:%date %n線程ID:[%thread] %n日誌級別: %-5level %n錯誤描述:%message%newline %n"/> </layout> </appender> <!--Info日誌--> <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="Log\\LogInfo\\" /> <param name="AppendToFile" value="true" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <param name="MaxFileSize" value="10240" /> <param name="MaxSizeRollBackups" value="100" /> <param name="StaticLogFileName" value="false" /> <param name="DatePattern" value="yyyy\\yyyyMM\\yyyyMMdd‘.txt‘" /> <param name="RollingStyle" value="Date" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%newline %n記錄時間:%date %n線程ID:[%thread] %n日誌級別: %-5level %n日誌描述:%message%newline %n"/> </layout> </appender> <!--監控日誌--> <appender name="MonitorAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="Log\\LogMonitor\\" /> <param name="AppendToFile" value="true" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <param name="MaxFileSize" value="10240" /> <param name="MaxSizeRollBackups" value="100" /> <param name="StaticLogFileName" value="false" /> <param name="DatePattern" value="yyyy\\yyyyMM\\yyyyMMdd‘.txt‘" /> <param name="RollingStyle" value="Date" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%newline %n記錄時間:%date %n線程ID:[%thread] %n日誌級別: %-5level %n跟蹤描述:%message%newline %n"/> </layout> </appender> <!--Error日誌--> <logger name="logerror"> <level value="ERROR" /> <appender-ref ref="AdoNetAppender_MySql"/> <appender-ref ref="RollingLogFileAppender" /> </logger> <!--Info日誌--> <logger name="loginfo"> <level value="INFO" /> <appender-ref ref="AdoNetAppender_MySql"/> <appender-ref ref="InfoAppender" /> </logger> <!--監控日誌--> <logger name="logmonitor"> <level value="WARN" /> <appender-ref ref="AdoNetAppender_MySql"/> <appender-ref ref="MonitorAppender" /> </logger> </log4net> </configuration>
其中appender中Name為AdoNetAppender_MySql的配置是配置連接數據庫的類型、連接字符串及插入數據庫的語句、語句對應的值等配置信息。
然後建立類代碼如下:
using System;
using System.Collections.Generic;

namespace Log4NetDemo
{
    /// <summary>
    /// 日誌配置
    /// </summary>
    public static class LogConfig
    {
/// <summary>
        /// 異常日誌語句
        /// </summary>
        /// <param name="ControllerName"></param>
        /// <param name="ActionName"></param>
        /// <param name="ActionParams"></param>
        /// <param name="HttpRequestHeaders"></param>
        /// <param name="HttpMethod"></param>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static string GetLogErrorString(string ControllerName = null, string ActionName = null, Dictionary<string, object> ActionParams = null, string HttpRequestHeaders = null, string HttpMethod = null, string ip = null)
        {

            return $@"
                 請求【{ControllerName}Controller】的【{ActionName}】
                 產生異常:
                 Action參數:{GetCollections(ActionParams)}
                 Http請求頭:{HttpRequestHeaders}
                 ip地址:{ip},
                請求類型:{HttpMethod}";
        }

        /// <summary>
        /// 獲取Action 參數
        /// </summary>
        /// <param name="Collections"></param>
        /// <returns></returns>
        public static string GetCollections(Dictionary<string, object> Collections)
        {
            string Parameters = string.Empty;
            if (Collections == null || Collections.Count == 0)
            {
                return Parameters;
            }
            foreach (string key in Collections.Keys)
            {
                Parameters += $"{key}={Collections[key]}&";
            }
            if (!string.IsNullOrWhiteSpace(Parameters) && Parameters.EndsWith("&"))
            {
                Parameters = Parameters.Substring(0, Parameters.Length - 1);
            }
            return Parameters;
        }
    }

    /// <summary>
    /// 日誌配置
    /// </summary>
    public class LoggerWebConfig
    {
        /// <summary>
        /// 控制器
        /// </summary>
        public string ControllerName { get; set; }
        /// <summary>
        /// 方法
        /// </summary>
        public string ActionName { get; set; }

        /// <summary>
        /// 開始時間
        /// </summary>
        public DateTime ExecuteStartTime { get; set; }

        /// <summary>
        /// 結束時間
        /// </summary>
        public DateTime ExecuteEndTime { get; set; }

        /// <summary>
        /// 請求的Action 參數
        /// </summary>
        public Dictionary<string, object> ActionParams { get; set; }

        /// <summary>
        /// Http請求頭
        /// </summary>
        public string HttpRequestHeaders { get; set; }

        /// <summary>
        /// 請求方式
        /// </summary>
        public string HttpMethod { get; set; }

        /// <summary>
        /// 請求的IP地址
        /// </summary>
        public string IP { get; set; }

        /// <summary>
        /// 返回監控語句
        /// </summary>
        /// <param name="mtype"></param>
        /// <returns></returns>
        public string GetInfoString()
        {
            string Msg = $@"
            Action執行時間監控:
            控制器名:{ControllerName}
            訪問方法:   {ActionName}
            開始時間:{ExecuteStartTime}
            結束時間:{ExecuteEndTime}
            總耗時間:{(ExecuteEndTime - ExecuteStartTime).TotalSeconds}秒
            請求參數:{LogConfig.GetCollections(ActionParams)}
            請求頭部:   {HttpRequestHeaders}
            請求地址:{IP}
            請求方式:   {HttpMethod}";
            return Msg;
        }

    }
}

以上類建好之後,建立一個Loggerhelper用來加載配置信息重寫寫入相應的日誌信息的方法。

using System;
using log4net;
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "~/Log4net.config", Watch = true)]
namespace Taihua.Log4
{
    /// <summary>
    /// 日誌
    /// </summary>
     public class LoggerHelper
    {
        /// <summary>
        /// 定義日誌模塊
        /// </summary>
        private static readonly ILog loginfo = LogManager.GetLogger("loginfo");
        private static readonly ILog logerror = LogManager.GetLogger("logerror");
        private static readonly ILog logwarn = LogManager.GetLogger("logmonitor");
        /// <summary>
        /// 錯誤日誌
        /// </summary>
        /// <param name="ErrorMsg">錯誤信息</param>
        /// <param name="ex">異常</param>
        public static void Error(string ErrorMsg, Exception ex = null)
        {
            if (ex != null)
            {
                logerror.Error(ErrorMsg, ex);
            }
            else
            {
                logerror.Error(ErrorMsg);
            }
        }

        /// <summary>
        /// 警告日誌
        /// </summary>
        /// <param name="Msg">錯誤信息</param>
        public static void Info(string Msg)
        {
            loginfo.Info(Msg);
        }

        /// <summary>
        /// 監控日誌
        /// </summary>
        /// <param name="Msg">錯誤信息</param>
        public static void Warn(string Msg)
        {
            logwarn.Warn(Msg);
        }

    }
}

在需要記錄日誌的地方使用如下代碼調用

      LoggerHelper.Info($"測試測試");
      LoggerHelper.Warn($"警告測試警告測試");
      LoggerHelper.Error($"錯誤測試錯誤測試");

最後建立一個demo數據庫及log4net的數據庫表,數據庫表代碼如下:

DROP TABLE IF EXISTS `loggerbackstage`;
CREATE TABLE `loggerbackstage`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `log_datetime` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0),
  `log_thread` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `log_level` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `log_logger` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `log_message` text CHARACTER SET utf8 COLLATE utf8_general_ci,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 16 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

然後就log4net日誌就可以記錄到文本文件中和數據庫中了。如果警告、錯誤、信息需要記錄到不同的表中,那麽需要配置不同的append節點,並且調用。

本文參考了:

https://blog.csdn.net/Javon_huang/article/details/77727389

https://www.cnblogs.com/wangqiideal/p/4692651.html

等博客,看得太多不一定記得下來。大致就是這兩篇吧,另外配置數據庫連接方式的時候不要指定mysql的版本 ,因為我指定版本的時候寫不進去,不知道是什麽原因。還有一點就是配置文件中的

<bufferSize value="1" />

是代表緩存大小,在沒達到緩存大小時,暫時不會存到數據庫中,當程序關閉之後會,將未插入數據庫的記錄加入到數據庫中。

關於log4net日誌寫入mysql數據庫記錄