program tip

외부 파일의 Log4Net 구성이 작동하지 않습니다.

radiobox 2020. 9. 9. 07:52
반응형

외부 파일의 Log4Net 구성이 작동하지 않습니다.


log4net을 사용하고 있으며 다른 섹션에서 수행 한 것처럼 외부 구성 파일에 구성을 지정하려고합니다. 이를 위해 App.config의 log4net 섹션을 다음과 같이 변경했습니다.

...
<section name="log4net" 
     type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
...
<log4net configSource="Log.config" />
...

그리고 Log.Config 파일 (App.config와 동일한 디렉토리)에는 다음이 있습니다.

<log4net>
  <appender name="General" type="log4net.Appender.FileAppender">
    <file value="myapp.log" />
    <layout type="log4net.Layout.SimpleLayout" />
  </appender>
  <root>
    <appender-ref ref="General" />
  </root>
</log4net>

그러나 앱을 실행하면 로그 파일이 생성되지 않고 로깅이 수행되지 않습니다. 콘솔에 출력되는 오류 메시지가 없습니다.

Log.config 파일의 내용을 App.config로 다시 이동하면 (위의 첫 번째 코드 줄 대체) 예상대로 작동합니다. 왜 외부 파일에서 작동하지 않는지 아십니까?


AssemblyInfo.cs파일에 다음 속성이 있습니까?

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

로깅 기능이 필요한 각 클래스의 시작 부분에 다음과 같이 코드를 작성합니다.

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

여기 에이 정보와 기타 정보가 포함 된 블로그 게시물이 있습니다 .


열려있는 결함 이 문제에 대한이. Log4Net은 구성 요소의 configSource 속성을 지원하지 않습니다. 순전히 구성 파일 솔루션을 사용하려면 appSettings에서 log4net.Config 키를 사용합니다.

1 단계 : 일반 구성 섹션 정의 포함 :

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

2 단계 : appSettings에서 매직 log4net.Config 키를 사용합니다.

<appSettings>
      <add key="log4net.Config" value="log4net.simple.config" />
</appSettings>

3 단계 : configSource 처리를 수정하는 패치를 제공합니다.


놓친 단계는

log4net.Config.XmlConfigurator.Configure(); 

그러면 configSource가 사용됩니다. GetLogger ()를 호출하기 전에 한 번 호출해야합니다.


log4net.config 파일이 다음 속성으로 설정되어 있는지 확인합니다.

빌드 액션 : 콘텐츠

출력 디렉토리에 복사 : 항상 복사


어느 쪽이든,

<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<appSettings>
<add key="log4net.Config" value="Log4Net.config" />
</appSettings>

아니면 그냥

log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo("Log4Net.config"));

In both cases the file,Log4Net.config, should be there in output directory. You can do this by setting Log4Net.config file properties in solution explorer. Build Action - Content and Copy to Output Directory - Copy always


Watch out for this issue...

In my case everything was configured correctly. The problem is that I used Web Deploy inside Visual Studio 2013 to upload the site to WinHost.com and it reset the ACLs on the server. This in turn revoked all permission on folders and files - log4net could not write the file.

You can read more about it here:

How to stop Web Deploy/MSBuild from messing up server permissions

I asked the support team there to reset the ACLs and then log4net started spitting logs. :)


Assuming you had an external config file called log4net.config that is copied to your deploy directory you can configure it like so:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Reflection;

using log4net;

namespace MyAppNamespace {
    static class Program {
        //declare it as static and public so all classes in the project can access it
        //like so: Program.log.Error("got an error");
        public static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() {
             //configure it to use external file
            log4net.Config.XmlConfigurator.Configure(new Uri(Application.StartupPath + "\\log4net.config"));
            //use it
            log.Debug("#############   STARING APPLICATION    #################");


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormMain());
        }
    }
}

I had the same problem, besides having

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net")]

in the running project, I also had the following line in a reference project:

[assembly: log4net.Config.XmlConfigurator]

When I removed this line in the referenced projects, the logs start to appear.


It is also possible to turn on a Debug mode for log4net. Insert this into the App.config file:

 <appSettings>
      <add key="log4net.Internal.Debug" value="true"/>
 </appSettings>
 <system.diagnostics>
      <trace autoflush="true">
      <listeners>
           <add
             name="textWriterTraceListener"
             type="System.Diagnostics.TextWriterTraceListener"
             initializeData="link\to\your\file.log" />
      </listeners>
      </trace>
 </system.diagnostics>

and you will at least get error messages, from which you can derive what exactly went wrong. In my case I simply forgot to set Copy to output directory to Copy Always.


@Mitch, It turns out there is a file with the [assembly:...] declaration, but it did not have the ConfigFile property.

Once I added it and pointed it to Log.config, it started working. I would have thought that it would work like all the other config sections (ie AppSettings) and accept external config files with no modification.

We don't have the second statement you mentioned, as we wrap it in a global static log provider.


In my case I got this error message:

log4net: config file [C:\........\bin\Debug\log4net.config] not found.

And log4net.config the file was in Visual Studio 2017 project, but when I checked the file in bin\Debug folder I could not find it.

My original assembly setup was like this:

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

After some research time, I change it to the following and it works:

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

  1. add following to AssemblyInfo.cs

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config")]

  1. Make sure log4net.config is included in project
  2. In properties of log4net.config

change Copy to Output Dirctory to Copy if newer

  1. Double check log level level value="ALL"

참고URL : https://stackoverflow.com/questions/445976/log4net-config-in-external-file-does-not-work

반응형