记录不起作用,尽管没有错误

时间:2019-07-03 09:02:01

标签: .net logging log4net nlog

在项目同时记录日志文件之前,我曾使用过nlog和log4net系统。没问题但是,我正在尝试记录文件。首先,我尝试了log4net,但是它不起作用,并且没有错误。然后,我从项目中清除log4net代码。之后,我安装了nlog软件包。我再次尝试登录到文件。它不像log4net那样工作。 这是我的log4net代码:

App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <!--  log4net  -->
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a" />

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="E:\IDG.log" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="1MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
    </root>
  </log4net>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

然后我将[assembly: log4net.Config.XmlConfigurator(ConfigFile = "App.config", Watch = true)]行写到assembly.Info

然后我写了Program.cs文件

  class Program {
            private static readonly ILog log =
                 LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            static void Main(string[] args) {  
                  log.Info("This is an informational message");  

                  Console.ReadKey();
            }
      }

log4net无法正常工作后。我清理了这些代码和log4net软件包。我尝试了nlog。 这是我的nlog代码:

Nlog.Config

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  <!-- optional, add some variables
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
  <variable name="logFilePath" value="D:\IDG.log" />


  <variable name="myvar" value="myvalue"/>

  <!--
  See https://github.com/nlog/nlog/wiki/Configuration-file
  for information on customizing logging rules and outputs.
   -->
  <targets> 

      <target name="logfile"  xsi:type="File" fileName="${logFilePath}" layout="${longdate}   LEVEL=${level:upperCase=true}: ${message}" keepFileOpen="true" />

    <!--
    add your targets here
    See https://github.com/nlog/NLog/wiki/Targets for possible targets.
    See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
    -->

    <!--
    Write events to a file with the date in the filename.
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    -->
  </targets>

  <rules>
    <rules>

      <logger name="*" minlevel="Info" writeTo="logfile" /> 
      <logger name="*" minlevel="Warn" writeTo="file"/>

    </rules>
    <!-- add your logging rules here -->

    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    <logger name="*" minlevel="Debug" writeTo="f" />
    -->
  </rules>
</nlog>

还有我的program.cs文件:

        private static Logger log = LogManager.GetCurrentClassLogger(); 

            static void Main(string[] args) {
                  log.Trace("This is a trace message"); 
                  log.Debug("This is a debug message"); 
                  log.Info("This is an informational message"); 
                  log.Warn("This is a warning message");  
                  log.Error("This is an error message"); 
                  log.Fatal("This is a fatal message");

                  Console.ReadKey();
            }
      }

这两个日志记录不起作用。我在哪里错了?

1 个答案:

答案 0 :(得分:0)

关于您的Log4net设置。

由于所有设置都在App.config文件中,因此您不必在XmlConfigurator属性中指定文件名。
如果没有给出,Log4net将寻找与您的应用程序名称匹配的配置文件,例如。对于MyApplication.exe,它将是MyApplication.exe.config
这是必须的,因为App.config在构建时已重命名。

代替

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "App.config", Watch = true)]

只需使用

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

来自Log4net documentation

// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfigurator(Watch=true)]
// This will cause log4net to look for a configuration file
// called TestApp.exe.config in the application base
// directory (i.e. the directory containing TestApp.exe)
// The config file will be watched for changes.