Log4net自定义配置说明及排错方法

1、日志记录到数据库时,如对应日志表无日志,可通过如下方式排查:

       A、检查数据库的连接事件日志,如无任何事件,则表明数据库连接失败,这时需要排查log4net.config的配置;如有事件,则将对应Insert Sql直接在数据库内执行,排查对应SQL错误即可。

       B、在AspnetCore中使用时Microsoft.Extensions.Logging.Log4Net.AspNetCore包时,如SQL Server的连接驱动设置为 System.Data.SqlClient时,会数据库连接失败,且系统捕获不到异常。需要必须使用Microsoft.Data.SqlClient.

2、如需要开发自定义参数的Logger,可以参考如下代码:

A、 定义工具类

using log4net;
using log4net.Core;
using log4net.Layout;
using System.Reflection;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace XD.OIDC.Core
{

    public class XDLogPatternLayout : PatternLayout
    {
        public XDLogPatternLayout()
        {
            this.AddConverter("XDLayout", typeof(XDLogConvert));
        }
    }

    public class XDLogConvert : log4net.Layout.Pattern.PatternLayoutConverter
    {
        protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            if (!string.IsNullOrEmpty(Option))
            {
                object obj = loggingEvent.MessageObject;
                if (obj != null)
                {
                    PropertyInfo info = obj.GetType().GetProperty(Option);
                    if (info != null)
                    {
                        object custMsg = info.GetValue(obj, null);
                        writer.Write(custMsg);
                    }
                }
            }
        }
    }

    public class XDLogModel
    {
        public string IP { get; set; } = "localhost";

        public string UserName { get; set; } = "张三";

        public string Msg { get; set; } = "XDLog Message";
    }

    public class LogHelper
    {
        private static readonly log4net.ILog logDefault = log4net.LogManager.GetLogger("XDLOG");

        public static XDLogModel GetXDLogModel()
        {
            XDLogModel model = new XDLogModel();
            return model;
        }

        public static void LogInfo(XDLogModel msg) {
            logDefault.InfoFormat($"IP:{msg.IP},UserName:{msg.UserName},Mesage:{msg.Msg}", msg);
            logDefault.Info(msg );
        }
    }
}

B、在需要的位置记录日志

 XD.OIDC.Core.LogHelper.LogInfo( new XD.OIDC.Core.XDLogModel { IP="localhost", UserName = "张三",Msg = "李四"});         

C、Log4net.config文件配置

<log4net>    
    <appender name="SqlServer_AdoNetAppender"
              type="log4net.Appender.AdoNetAppender">
        <!--每次缓存的消息数,bufferSize=0时,表示每条日志立即写入DB-->
        <bufferSize value="0"/>
        <connectionType value="Microsoft.Data.SqlClient.SqlConnection,Microsoft.Data.SqlClient, Version=5.0.0.0, Culture=neutral, PublicKeyToken=23ec7fc2d6eaa4a5"/>
        <connectionString value="Data Source=.\sqlexpress;Initial Catalog=XDLog;User ID=sa;Password=123456;Trust Server Certificate=True"/>
        <commandText value="INSERT INTO Sys_Log(Date,Thread,Level,Logger,Message,Exception) VALUES (@date, @thread, @level, @logger, @message, @exception)"/>
        <parameter>
            <parameterName value="@date"/>
            <dbType value="DateTime"/>
            <layout type="log4net.Layout.RawTimeStampLayout"/>
        </parameter>
        <parameter>
            <parameterName value="@thread"/>
            <dbType value="String"/>
            <size value="255"/>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%thread"/>
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@level"/>
            <dbType value="String"/>
            <size value="50"/>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%level"/>
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@logger"/>
            <dbType value="String"/>
            <size value="255"/>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%logger"/>
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@message"/>
            <dbType value="String"/>
            <size value="4000"/>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%message"/>
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@exception"/>
            <dbType value="String"/>
            <size value="2000"/>
            <layout type="log4net.Layout.ExceptionLayout"/>
        </parameter>
    </appender>
    <appender name="SqlServer_AdoNet_Http_Appender"
              type="log4net.Appender.AdoNetAppender">
        <!--每次缓存的消息数,bufferSize=0时,表示每条日志立即写入DB-->
        <bufferSize value="0"/>
        <connectionType value="Microsoft.Data.SqlClient.SqlConnection,Microsoft.Data.SqlClient, Version=5.0.0.0, Culture=neutral, PublicKeyToken=23ec7fc2d6eaa4a5"/>
        <connectionString value="Data Source=.\sqlexpress;Initial Catalog=XDLog;User ID=sa;Password=123qwe!@#;Trust Server Certificate=True"/>
        <commandText value="INSERT INTO Sys_Log_Http(Date,Thread,Level,Logger,Message,Exception) VALUES (@date, @thread, @level, @logger, @message, @exception)"/>
        <parameter>
            <parameterName value="@date"/>
            <dbType value="DateTime"/>
            <layout type="log4net.Layout.RawTimeStampLayout"/>
        </parameter>
        <parameter>
            <parameterName value="@thread"/>
            <dbType value="String"/>
            <size value="255"/>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%thread"/>
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@level"/>
            <dbType value="String"/>
            <size value="50"/>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%level"/>
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@logger"/>
            <dbType value="String"/>
            <size value="255"/>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%logger"/>
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@message"/>
            <dbType value="String"/>
            <size value="4000"/>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%message"/>
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@exception"/>
            <dbType value="String"/>
            <size value="2000"/>
            <layout type="log4net.Layout.ExceptionLayout"/>
        </parameter>
    </appender>
    <appender name="Console"
              type="log4net.Appender.ConsoleAppender">
        <layout type="log4net.Layout.PatternLayout">
            <!-- Pattern to output the caller's file name and line number -->
            <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception"/>
        </layout>
    </appender>    
    <appender name="ConsoleAppender"
              type="log4net.Appender.ManagedColoredConsoleAppender">
        <mapping>
            <level value="ERROR"/>
            <foreColor value="Red"/>
        </mapping>
        <mapping>
            <level value="WARN"/>
            <foreColor value="Yellow"/>
        </mapping>
        <mapping>
            <level value="INFO"/>
            <foreColor value="White"/>
        </mapping>
        <mapping>
            <level value="DEBUG"/>
            <foreColor value="Green"/>
        </mapping>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception"/>
        </layout>
    </appender>
    <appender name="XDAdo_Appender"
              type="log4net.Appender.AdoNetAppender">
        <!--每次缓存的消息数,bufferSize=0时,表示每条日志立即写入DB-->
        <bufferSize value="0"/>
        <connectionType value="Microsoft.Data.SqlClient.SqlConnection,Microsoft.Data.SqlClient, Version=5.0.0.0, Culture=neutral, PublicKeyToken=23ec7fc2d6eaa4a5"/>
        <connectionString value="Data Source=.\sqlexpress;Initial Catalog=XDLog;User ID=sa;Password=123qwe!@#;Trust Server Certificate=True"/>
        <commandText value="INSERT INTO Sys_Log_Xd(Date,IP,UserName,Msg) VALUES (getdate(), @IP, @UserName,@Msg)"/>
        <parameter>
            <parameterName value="@IP"/>
            <dbType value="String"/>
            <size value="255"/>
            <layout type="XD.OIDC.Core.XDLogPatternLayout">
                <XDLogConvert value="%IP"/>
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@UserName"/>
            <dbType value="String"/>
            <size value="255"/>
            <layout type="XD.OIDC.Core.XDLogPatternLayout">
                <XDLogConvert value="%UserName"/>
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@Msg"/>
            <dbType value="String"/>
            <size value="255"/>
            <layout type="XD.OIDC.Core.XDLogPatternLayout">
                <XDLogConvert value="%Msg"/>
            </layout>
        </parameter>
        <!--<layout type="XD.OIDC.Core.XDLogPatternLayout">
        <conversionPattern value="%XDLayout{@IP} %XDLayout{@UserName} %XDLayout{@Msg} " />
      </layout>-->
    </appender>
    <logger name="Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware">
        <!--
      日志的Level设置值:ALL、EBUG、INFO、WARN、ERROR、FATAL、OFF 如需高级调试设置以及log4net的高级配置请参见log4net文档
      -->
        <level value="INFO"/>
        <appender-ref ref="SqlServer_AdoNet_Http_Appender"/>
    </logger>
    <logger name="XDLOG">
        <level value="INFO"/>
        <appender-ref ref="XDAdo_Appender"/>
    </logger>
    <root>
        <!--日志的Level设置值:ALL、DEBUG、INFO、WARN、ERROR、FATAL、OFF 如需高级调试设置以及log4net的高级配置请参见log4net文档-->
        <level value="TRACE"/>
        <appender-ref ref="RollingFile"/>
        <appender-ref ref="TraceAppender"/>
        <appender-ref ref="ConsoleAppender"/>
        <appender-ref ref="SqlServer_AdoNetAppender"/>
    </root>
</log4net>

 

posted @ 2024-12-30 20:50  千年海岩  阅读(7)  评论(0编辑  收藏  举报