.net core 中使用Log4net輸出日誌到Mysql資料庫中

STR少寒發表於2021-01-12

.net core 中使用Log4net輸出日誌到資料庫中去

1.使用Nuget安裝log4net 和 mysql.data

2.設定log4net 的配置檔案 log4net.config

image-20210112224320408

image-20210112223527630

image-20210112223957164

  • 可以設定多個倉庫進而插入到資料不同的表中
<?xml version="1.0" encoding="utf-8" ?>

<configuration>
<log4net>
	<!--Info日誌-->
	<logger name="loginfo">
		<level value="INFO" />
		<appender-ref ref="AdoNetAppender_MySql"/>
	</logger>
	<!-- name屬性指定其名稱,type則是log4net.Appender名稱空間的一個類的名稱,意思是,指定使用哪種介質-->
	<appender name="AdoNetAppender_MySql" type="log4net.Appender.ADONetAppender">
		<!--日誌快取寫入條數 設定為0時只要有一條就立刻寫到資料庫-->
		<bufferSize value="1" />
		<!--日誌資料庫連線串-->
		<connectionType value="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" />
		<connectionString value="server=localhost;userid=root;pwd=123456;port=3306;database=hipmysql;SslMode=none" />
		
		<!--日誌資料庫指令碼-->
		<commandText value="INSERT INTO LogDetails (LogDate,LogThread,LogLevel,LogLogger,LogActionClick,LogMessage,UserName,UserIP) VALUES (@log_date, @thread, @log_level, @logger, @ActionsClick, @message,@UserName,@UserIP)" />
		<!--日誌時間LogDate -->
		<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>
		<!--日誌型別LogLevel -->
		<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="Utility.Log4net.ActionLayoutPattern">
				<!--<conversionPattern value="%message" />-->
				 <conversionPattern value="%actionInfo{Message}" />
			</layout>
		</parameter>
		<parameter>
			<parameterName value="@ActionsClick" />
			<dbType value="String" />
			<size value="4000" />
			<layout type="log4net.Layout.ExceptionLayout" />
			<!--<layout type="Log4NetApply.MyLayout" >
				<conversionPattern value = "%property{ActionsClick}"/>
			</layout>-->
		</parameter>
		<!--自定義UserName-->
		<parameter>
			<parameterName value="@UserName" />
			<dbType value="String" />
			<size value="30" />
			<layout type="Utility.Log4net.ActionLayoutPattern" >
				<conversionPattern value = "%actionInfo{UserName}"/>
			</layout>
		</parameter>
		<parameter>
			<parameterName value="@UserIP" />
			<dbType value="String" />
			<size value="20" />
			<layout type="Utility.Log4net.ActionLayoutPattern" >
				<conversionPattern value = "%actionInfo{UserIP}"/> 
			</layout>
		</parameter>
	</appender>
</log4net>
</configuration>

3.在mysql 中建立對應的資料表

4.建立自定義欄位的實體類

using System;
using System.Collections.Generic;
using System.Text;

namespace Utility.Log4net
{
    public class ActionLoggerInfo
    {
        public string UserName { get; set; }
        public string UserIP { get; set; }
        public string Message { get; set; }

        public ActionLoggerInfo(string username, string userip,string message)
        {
            this.UserName = username;
            this.UserIP = userip;
            this.Message = message;
        }

    }
}

5.建立轉換器類ActionConverter

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using log4net.Layout;
using log4net.Layout.Pattern;
using log4net.Core;

namespace Utility.Log4net
{
    public class ActionConverter: PatternLayoutConverter
    {
        protected override void Convert(System.IO.TextWriter writer, LoggingEvent loggingEvent)
        {
            var actionInfo = loggingEvent.MessageObject as ActionLoggerInfo;

            if (actionInfo == null)
            {
                writer.Write("");
            }
            else
            {
                switch (this.Option.ToLower())
                {
                    case "username":
                        writer.Write(actionInfo.UserName);
                        break;
                    case "userip":
                        writer.Write(actionInfo.UserIP);
                        break;
                    case "message":
                        writer.Write(actionInfo.Message);
                        break;
                    default:
                        writer.Write("");
                        break;
                }
            }
        }
    }
}

6.繼承log4net 的PatternLayout ,建立自定義的屬性類

image-20210112225205967

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using log4net.Layout;
using log4net.Layout.Pattern;
using log4net.Core;

namespace Utility.Log4net
{
    public class ActionLayoutPattern : PatternLayout
    {
        public ActionLayoutPattern()
        {
            this.AddConverter("actionInfo", typeof(ActionConverter));
        }
    }
}

7.建立日誌幫助類loghelper

using log4net;
using log4net.Config;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Utility.Log4net
{
    public class LogHelper
    {
        public static readonly LogHelper Instance = new LogHelper();
        private static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
        //public static log4net.ILog loginfo = LogManager.GetLogger("loginfo");

        public LogHelper() {
            string text = "";
            text = System.AppDomain.CurrentDomain.BaseDirectory + "config\\Log4Net.config";
            XmlConfigurator.ConfigureAndWatch(new FileInfo(text));
        }

        private static ActionLoggerInfo _message = null;
        private static log4net.ILog _log;

        public static log4net.ILog Log
        {
            get
            {
                if (_log == null)
                {
                    _log = LogManager.GetLogger("OperateLogger");
                }
                return _log;
            }
        }

        public static void Debug()
        {
            if (Log.IsDebugEnabled)
            {
                Log.Debug(_message);
            }
        }
        public static void Error()
        {
            if (Log.IsErrorEnabled)
            {
                Log.Error(_message);
            }
        }
        public static void Fatal()
        {
            if (Log.IsFatalEnabled)
            {
                Log.Fatal(_message);
            }
        }
        public static void Info()
        {
            if (loginfo.IsInfoEnabled)
            {
                loginfo.Info(_message);
            }
        }
        public static void Warn()
        {
            try
            {
                if (Log.IsWarnEnabled)
                {
                    Log.Warn(_message);
                }
            } catch (Exception e)
            {
                var t = e;
            }
        }

        public static void SaveMessage(string username, string userip, string message, int level)
        {
            _message = new ActionLoggerInfo(username, userip, message);
            switch (level)
            {
                case 1: Info(); break;
                case 2: Warn(); break;
                case 3: Error(); break;
                case 4: Fatal(); break;
                default: break;
            }
        }
    }
}

參考部落格:

相關文章