如何使用 Log4net 进行日志记录?

Posted

技术标签:

【中文标题】如何使用 Log4net 进行日志记录?【英文标题】:How to logging with Log4net? 【发布时间】:2016-06-05 08:43:21 【问题描述】:

我尝试使用 log4net 登录我的 wep 项目。对数据库使用 EntityFramework 和 LINQ。我将这些添加到 web.config 文件中

<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>

 <log4net>
    <logger name ="DBLogger">
      <level value="ALL"></level>
      <appender-ref ref="AdoNetAppender" />
    </logger>
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="100" />
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <connectionString value="data source=localhost;initial catalog=CATALOG_NAME;persist security info=False;user id=DB_USER;password=DB_PASSWORD;MultipleActiveResultSets=True;App=EntityFramework" />

      <commandText value="INSERT INTO RCN_OPERATION_LOGS ([DATE],[THREAD],[LEVEL],[LOGGER],[MESSAGE],[EXCEPTION]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
      <parameter>
        <parameterName value="@log_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 ip=%propertyip" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@log_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>
  </log4net>



 <system.diagnostics>
    <trace autoflush="true">
      <listeners>
        <add
            name="textWriterTraceListener"  type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\HttpRoot\FITMutabakat\log4net_debug.txt" />
      </listeners>
    </trace>
  </system.diagnostics>

<appSettings>
    <add key="log4net.Internal.Debug" value="true" />
    <add key="log4net.Config" value="log4net.config"/>
    <add key="log4net.Config.Watch" value="True"/>
</appSettings>

将此行添加到 AssemblyInfo.cs:

[程序集:log4net.Config.XmlConfigurator(ConfigFile = "web.config", Watch = true)]

还有Global.asax.cs:

  protected void Application_Start(object sender, EventArgs e)
    
        log4net.Config.XmlConfigurator.Configure();
    

我创建了一个这样的 Logger 类;

using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FITMutabakat.BLL.Base

    public class Logger : Manager
    
        private static readonly ILog logger = LogManager.GetLogger("DBLogger");

        public void AddLog(string user, string loggertype, string logprocess, string mesaj, string data, Exception ex)
        
            LoggerAdd(logger, loggertype, logprocess, user, data, mesaj, ex);
            this.Context.SaveChanges();
        


        public static void LoggerAdd(log4net.ILog logger, string LoggerType, string LogProcess, string User, string Data, string LogMessage, System.Exception Ex)
        
            try
            
                if (LoggerType == "InfoFormat")
                
                    object[] args = new object[4];
                    logger.Info("sdf");

                    if (Data != null)
                    
                        args[0] = LogProcess;
                        args[1] = User;
                        args[2] = Data;
                        args[3] = LogMessage;
                        logger.InfoFormat("[0] [1] [2] [3]", args);
                    
                    else
                    
                        args[0] = LogProcess;
                        args[1] = User;
                        args[2] = LogMessage;
                        logger.InfoFormat("[0] [1] [2] ", args);
                    
                
                else if (LoggerType == "Fatal")
                
                    if (Data != null)
                    
                        object[] args = new object[4];
                        args[0] = LogProcess;
                        args[1] = User;
                        args[2] = Data;
                        args[3] = LogMessage;
                        string ermes = string.Format("[0] [1] [2] [3]", args);
                        logger.Fatal(ermes, Ex);
                    
                    else
                    
                        object[] args = new object[4];
                        args[0] = LogProcess;
                        args[1] = User;
                        args[2] = LogMessage;
                        string ermes = string.Format("[0] [1] [2] ", args);
                        logger.Fatal(ermes, Ex);
                    
                
            
            catch (Exception ex)
            
                throw ex;
            
        
    

用户登录时调用Logger类:

Logger logger = new Logger();
logger.AddLog(oUser.USERNAME, "InfoFormat", "KullanıcıIslem", "Kullanıcı sisteme giriş yaptı.", null, null);

但是任何日志都添加到数据库中。哪里有问题,没找到。 当程序运行 log4net 时,将这些写入调试文件但出现任何错误。

log4net: log4net assembly [log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a]. Loaded from [C:\Users\admin\AppData\Local\Temp\Temporary ASP.NET Files\vs\05d71218\bc109529\assembly\dl3\d1df1039\3eae6e67_6b57d101\log4net.dll]. (.NET Runtime [4.0.30319.34209] on Microsoft Windows NT 6.2.9200.0)
log4net: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository for assembly [FITMutabakat, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]
log4net: Assembly [FITMutabakat, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [C:\Users\admin\AppData\Local\Temp\Temporary ASP.NET Files\vs\05d71218\bc109529\assembly\dl3\a6a085ea\52e3a93b_3a6ed101\FITMutabakat.dll]
log4net: Assembly [FITMutabakat, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.
log4net: Assembly [FITMutabakat, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]
log4net: configuring repository [log4net-default-repository] using file [C:\HttpRoot\FITMutabakat\FITMutabakat\web.config] watching for file updates
log4net: configuring repository [log4net-default-repository] using file [C:\HttpRoot\FITMutabakat\FITMutabakat\web.config]
log4net: configuring repository [log4net-default-repository] using stream
log4net: loading XML configuration
log4net: Configuring Repository [log4net-default-repository]
log4net: Configuration update mode [Merge].
log4net: Retrieving an instance of log4net.Repository.Logger for logger [DBLogger].
log4net: Setting [DBLogger] additivity to [True].
log4net: Logger [DBLogger] Level string is [ALL].
log4net: Logger [DBLogger] level set to [name="ALL",value=-2147483648].
log4net: Loading Appender [AdoNetAppender] type: [log4net.Appender.AdoNetAppender]
log4net: Setting Property [BufferSize] to Int32 value [100]
log4net: Setting Property [ConnectionType] to String value [System.Data.SqlClient.SqlConnection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]
log4net: Setting Property [ConnectionString] to String value [data source=localhost;initial catalog=MUTABAKAT_DEV;persist security info=False;user id=sa;password=369900;MultipleActiveResultSets=True;App=EntityFramework]
log4net: Setting Property [CommandText] to String value [INSERT INTO RCN_OPERATION_LOGS ([DATE],[THREAD],[LEVEL],[LOGGER],[MESSAGE],[EXCEPTION]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)]
log4net: Setting Property [ParameterName] to String value [@log_date]
log4net: Setting Property [DbType] to DbType value [DateTime]
log4net: Setting Property [Layout] to object [log4net.Layout.RawTimeStampLayout]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@thread]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [255]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%thread ip=%propertyip]
log4net: Converter [thread] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ ip=] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [property] Option [ip] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@log_level]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [50]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%level]
log4net: Converter [level] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@logger]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [255]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%logger]
log4net: Converter [logger] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@message]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [4000]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%message]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@exception]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [2000]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Created Appender [AdoNetAppender]
log4net: Adding appender named [AdoNetAppender] to logger [DBLogger].
log4net: Hierarchy Threshold []
log4net: Loading and watching configuration for default repository from AppSettings specified Config path [C:\HttpRoot\FITMutabakat\FITMutabakat\log4net.config]
log4net: configuring repository [log4net-default-repository] using file [C:\HttpRoot\FITMutabakat\FITMutabakat\log4net.config] watching for file updates
log4net: configuring repository [log4net-default-repository] using file [C:\HttpRoot\FITMutabakat\FITMutabakat\log4net.config]
log4net: configuring repository [log4net-default-repository] using stream
log4net: loading XML configuration
log4net: Configuring Repository [log4net-default-repository]
log4net: Configuration update mode [Merge].
log4net: Logger [root] Level string is [ALL].
log4net: Logger [root] level set to [name="ALL",value=-2147483648].
log4net: Loading Appender [AdoNetAppender] type: [log4net.Appender.AdoNetAppender]
log4net: Setting Property [BufferSize] to Int32 value [100]
log4net: Setting Property [ConnectionType] to String value [System.Data.SqlClient.SqlConnection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]
log4net: Setting Property [ConnectionString] to String value [data source=localhost;initial catalog=MUTABAKAT_DEV;persist security info=False;user id=sa;password=369900;MultipleActiveResultSets=True;App=EntityFramework]
log4net: Setting Property [CommandText] to String value [INSERT INTO RCN_OPERATION_LOGS ([DATE],[THREAD],[LEVEL],[LOGGER],[MESSAGE],[EXCEPTION]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)]
log4net: Setting Property [ParameterName] to String value [@log_date]
log4net: Setting Property [DbType] to DbType value [DateTime]
log4net: Setting Property [Layout] to object [log4net.Layout.RawTimeStampLayout]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@thread]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [255]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%thread ip=%propertyip]
log4net: Converter [thread] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ ip=] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [property] Option [ip] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@log_level]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [50]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%level]
log4net: Converter [level] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@logger]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [255]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%logger]
log4net: Converter [logger] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@message]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [4000]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%message]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@exception]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [2000]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Created Appender [AdoNetAppender]
log4net: Adding appender named [AdoNetAppender] to logger [root].
log4net: Hierarchy Threshold []
log4net: configuring repository [log4net-default-repository] using .config file section
log4net: Application config file is [C:\HttpRoot\FITMutabakat\FITMutabakat\web.config]
log4net: Configuring Repository [log4net-default-repository]
log4net: Configuration update mode [Merge].
log4net: Retrieving an instance of log4net.Repository.Logger for logger [DBLogger].
log4net: Setting [DBLogger] additivity to [True].
log4net: Logger [DBLogger] Level string is [ALL].
log4net: Logger [DBLogger] level set to [name="ALL",value=-2147483648].
log4net: Loading Appender [AdoNetAppender] type: [log4net.Appender.AdoNetAppender]
log4net: Setting Property [BufferSize] to Int32 value [100]
log4net: Setting Property [ConnectionType] to String value [System.Data.SqlClient.SqlConnection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]
log4net: Setting Property [ConnectionString] to String value [data source=localhost;initial catalog=MUTABAKAT_DEV;persist security info=False;user id=sa;password=369900;MultipleActiveResultSets=True;App=EntityFramework]
log4net: Setting Property [CommandText] to String value [INSERT INTO RCN_OPERATION_LOGS ([DATE],[THREAD],[LEVEL],[LOGGER],[MESSAGE],[EXCEPTION]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)]
log4net: Setting Property [ParameterName] to String value [@log_date]
log4net: Setting Property [DbType] to DbType value [DateTime]
log4net: Setting Property [Layout] to object [log4net.Layout.RawTimeStampLayout]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@thread]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [255]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%thread ip=%propertyip]
log4net: Converter [thread] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ ip=] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [property] Option [ip] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@log_level]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [50]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%level]
log4net: Converter [level] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@logger]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [255]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%logger]
log4net: Converter [logger] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@message]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [4000]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%message]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Setting Property [ParameterName] to String value [@exception]
log4net: Setting Property [DbType] to DbType value [String]
log4net: Setting Property [Size] to Int32 value [2000]
log4net: Setting Property [Layout] to object [log4net.Layout.Layout2RawLayoutAdapter]
log4net: Setting Collection Property [AddParameter] to object [log4net.Appender.AdoNetAppenderParameter]
log4net: Created Appender [AdoNetAppender]
log4net: Adding appender named [AdoNetAppender] to logger [DBLogger].
log4net: Hierarchy Threshold []
log4net: Creating repository for assembly [FITMutabakat.BLL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]
log4net: Assembly [FITMutabakat.BLL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [C:\Users\admin\AppData\Local\Temp\Temporary ASP.NET Files\vs\05d71218\bc109529\assembly\dl3\4f082a23\1998a73a_3a6ed101\FITMutabakat.BLL.dll]
log4net: Assembly [FITMutabakat.BLL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.
log4net: Assembly [FITMutabakat.BLL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: repository [log4net-default-repository] already exists, using repository type [log4net.Repository.Hierarchy.Hierarchy]

【问题讨论】:

你的帖子太短了。 看这个。我找到的最好的 log4net 教程。 youtube.com/watch?v=2lAdQ_QwNww 您的数据库密码在 log4net 输出中。 【参考方案1】:

我可以看到一些可能丢失的内容,这可能是您的记录器无法正常工作的原因。

首先,在 Global.asax.cs 文件中,我会:

    private static readonly ILog log = LogManager.GetLogger(typeof(MvcApplication));

    void Application_Error(Object sender, EventArgs e)
    
        Exception ex = Server.GetLastError().GetBaseException();
        log.Error("App_Error", ex);
    

    protected void Application_Start()
    
        log4net.Config.XmlConfigurator.Configure();
    

然后在 web.config 文件中,我看不到您在任何地方的 log4net 标记中都有 &lt;root&gt; 标记。看起来你正试图用&lt;logger&gt; 来做这件事,我不确定它来自哪里。此外,我会将缓冲区大小从 100 更改为 1(因此,与其在写入数据库之前等待 100,不如将其写入每个日志)。我会将整个部分更改为:

<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<log4net debug="true">
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
  <bufferSize value="1" />
  <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  <connectionString value="data source=localhost;initial catalog=CATALOG_NAME;persist security info=False;user id=DB_USER;password=DB_PASSWORD;MultipleActiveResultSets=True;App=EntityFramework" />

  <commandText value="INSERT INTO RCN_OPERATION_LOGS ([DATE],[THREAD],[LEVEL],[LOGGER],[MESSAGE],[EXCEPTION]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
  <parameter>
    <parameterName value="@log_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 ip=%propertyip" />
    </layout>
  </parameter>
  <parameter>
    <parameterName value="@log_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>

<root>
  <level value="ALL" />
  <appender-ref ref="AdoNetAppender" />
</root>
</log4net>

【讨论】:

以上是关于如何使用 Log4net 进行日志记录?的主要内容,如果未能解决你的问题,请参考以下文章

C# 使用Log4Net记录程序日志

如何使用 C# 中的 log4net 记录日志

Log4Net之记录日志到数据库

日志记录工具 log4net 的配置与使用

.Net Log4Net配置多文件日志记录

使用 log4net 或 NLog 的 WCF 日志记录/跟踪和活动 ID 传播