Ведение журнала не работает, хотя ошибки нет - PullRequest
0 голосов
/ 03 июля 2019

Я использовал системы 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)] строку для сборки. Информация

Тогда я написал в файл 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 голосов
/ 03 июля 2019

Относительно вашей настройки 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 документации :

// 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.
...