当前位置:Gxlcms > 数据库问题 > 关于log4net日志写入mysql数据库记录

关于log4net日志写入mysql数据库记录

时间:2021-07-01 10:21:17 帮助过:7人阅读

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数据库记录

标签:ons   插入   rsize   void   html   vat   arch   line   creat   

人气教程排行