简体   繁体   English

带有 AdoNetAppender 的 Log4Net - 没有任何反应

[英]Log4Net with AdoNetAppender - nothing happens

Description描述

I have a config file as a resource in my assembly and want to change the ConnectionString programmatically in my application.我的程序集中有一个配置文件作为资源,我想在我的应用程序中以编程方式更改 ConnectionString。

I load the configuration using log.net.Config.XmlConfigurator.Configure .我使用log.net.Config.XmlConfigurator.Configure加载配置。

I have some breakpoints and see that the configuration is loaded successfuly and the connectionstring is Data Source=localhost\SQLExpress;Initial Catalog=Log;Integrated Security=SSPI;我有一些断点,看到配置已成功加载,连接字符串为Data Source=localhost\SQLExpress;Initial Catalog=Log;Integrated Security=SSPI; (local SQLExpress). (本地 SQLExpress)。

Problem问题

Nothing happens, no exception and no log entry.没有任何反应,没有异常,也没有日志条目。 Any ideas.有任何想法吗。

using (Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MyNamespace.Properties.log4net.config"))
{ 
    // stream is NOT null
    log4net.Config.XmlConfigurator.Configure(stream);
}

Hierarchy hier = LogManager.GetRepository() as Hierarchy;

if (hier != null)
{
    //get ADONetAppender
    var adoAppender = (AdoNetAppender)hier.GetAppenders().Where(appender => appender.Name.Equals("AdoNetAppender", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

    if (adoAppender != null)
    {
        // update connectionstring
        adoAppender.ConnectionString = configuration.GetConnectionString(ConnectionStringNames.Log).ConnectionString;
        //refresh settings of appender
        adoAppender.ActivateOptions(); 
    }
}

ILog logger = LogManager.GetLogger("MyProject"); 
logger.Warn("Test");

content of the log.net.config file log.net.config文件的内容

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

  <log4net>
    <appender name="AdoNetAppender" type="log4net.Appender.ADONetAppender">
      <bufferSize value="1" />
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data,
  Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <connectionString value="[we will set this automatically at runtime]" />
      <commandText value="INSERT INTO Log ([Date],[Level],[Logger],[Message],[Exception])
  VALUES (@log_date, @log_level, @logger, @message, @exception)" />
      <parameter>
        <parameterName value="@log_date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout" />
      </parameter>
      <parameter>
        <parameterName value="@log_level" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%p" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@logger" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%c" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%m" />
        </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>
</configuration>

You can debug log4net by hooking into the log4net DebugAppender:您可以通过连接到 log4net DebugAppender 来调试 log4net:

Add a log4net app setting in your app.config file:在 app.config 文件中添加 log4net 应用设置:

<appSettings>
  <!-- log4net configuration when running in debug mode. -->    
  <add key="log4net.Internal.Debug" value="true" />   
</appSettings>

Add a debug appender in the log4net config:在 log4net 配置中添加调试 appender:

<appender name="DebugAppender" type="log4net.Appender.DebugAppender">
  <immediateFlush value="true" />
  <layout type="log4net.Layout.SimpleLayout" />
</appender>

Add the appender to the log4net config root:将 appender 添加到 log4net 配置根目录:

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

When you run your application, look in the output window of Visual Studio and you should see all the internal logging for log4net.运行应用程序时,查看 Visual Studio 的输出窗口,您应该会看到 log4net 的所有内部日志记录。 If not, then the log4net config file is never loading.如果没有,则永远不会加载 log4net 配置文件。

Edit编辑

If you can use a connection string from your app.config file, then remove the connection string from the log4net AdoNetAppender and just call the connection string by name:如果您可以使用 app.config 文件中的连接字符串,则从 log4net AdoNetAppender 中删除连接字符串,只需按名称调用连接字符串:

<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
  <bufferSize value="1" />
  <!-- note: you can use the 4.0 assembly -->
  <connectionType value="System.Data.SqlClient.SqlConnection,
              System.Data, 
              Version=4.0.0.0, 
              Culture=neutral, 
              PublicKeyToken=b77a5c561934e089" />
  <!-- This will retrieve a connection string by name from the app.config -->
  <connectionStringName value="ConnectionStringNameFromAppConfig" />
  <!-- snip -->
</appender>

Here are some things that I tried that worked out for me...以下是我尝试过的一些对我有用的事情......

  • I wasn't seeing anything because my <appender-ref ref="AdoNetAppender" /> didn't properly reference my <appender name="AdoNetAppender" ... /> in the Web.config .我没有看到任何东西,因为我的<appender-ref ref="AdoNetAppender" />没有在Web.config 中正确引用我的<appender name="AdoNetAppender" ... /> The 'AdoNetAppender' names need to match. 'AdoNetAppender' 名称需要匹配。

  • Added <bufferSize value="1" /> to the <appender name="AdoNetAppender" /> section of the Web.config<bufferSize value="1" />Web.config<appender name="AdoNetAppender" />部分

  • I created a user account with a password on the SQL server instead of using windows authentication.我在 SQL 服务器上创建了一个带有密码的用户帐户,而不是使用 Windows 身份验证。 Granted user access to perform selects and inserts on the table授予用户对表执行选择和插入的访问权限

  • In Global.asax.cs I initialize log4net using log4net.Config.XmlConfigurator.Configure();Global.asax.cs 中,我使用log4net.Config.XmlConfigurator.Configure();初始化 log4net log4net.Config.XmlConfigurator.Configure();

  • In my C# code I instantiate a new adoAppender object and call logger.Info("save to db");在我的 C# 代码中,我实例化了一个新的 adoAppender 对象并调用logger.Info("save to db");

The documentation on Apache's website is helpful as well ... http://logging.apache.org/log4net/release/config-examples.html#MS%20SQL%20Server Apache 网站上的文档也很有帮助... http://logging.apache.org/log4net/release/config-examples.html#MS%20SQL%20Server

Hope that saves somebody some time and frustration.希望可以节省一些时间和挫折。 Thanks!谢谢!

I had a log.net configuration running for years, that stopped logging to database this spring 2022. I solved it by specifying: size value="7" to a DateTime2 database parameter in the log.net configuration.我有一个运行了多年的 log.net 配置,它在 spring 2022 停止记录到数据库。我通过在 log.net 配置中为 DateTime2 数据库参数指定:size value="7" 来解决它。 Type in database: datetime2(7), not null. Why size on that type suddenly is madatory in log.net I don't know.在数据库中输入:datetime2(7),而不是 null。为什么那种类型的大小突然在 log.net 中是强制性的我不知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM