.net core 中使用Log4net输出日志到Mysql数据库中

.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;
            }
        }
    }
}

8.使用

image-20210112230153338

LogHelper.SaveMessage("re","re","re",1);

如需转载,请在文章显眼出标识作者及原文出处

参考博客:

posted @ 2021-01-12 23:00  STR少寒  阅读(1499)  评论(13编辑  收藏  举报