developer tip

log4net (로거 이름 지정)을 사용하는 올바른 방법

optionbox 2020. 10. 8. 07:57
반응형

log4net (로거 이름 지정)을 사용하는 올바른 방법


log4net을 구성하고 사용하는 두 가지 방법이 있습니다. 첫 번째는 내 어 펜더 및 관련 로거를 구성 할 수있는 경우입니다.

<!-- language: xml -->

<appender name="myLogAppender" type="log4net.Appender.RollingFileAppender" >
    <file value="Logs\myLog.log" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level - %message%n" />
    </layout>
</appender>

<logger name="myLog">
    <level value="All"></level>
    <appender-ref ref="myLogAppender" />
</logger>

그런 다음 로그에 무언가를 쓰고 싶을 때 다음을 수행 할 수 있습니다.

ILog log = LogManager.GetLogger("myLog");
log.Info("message");

이를 사용하는 또 다른 방법은 루트를 원하는만큼 상세하게 구성하는 것입니다.

<!-- language: xml -->

<root>
    <level value="Error" />
    <appender-ref ref="myLogAppender" />
</root>

이 경우 다음과 같은 메시지를 기록 할 수 있습니다.

ILog log = LogManager.GetLogger(typeof(Bar));
log.Info("message");

두 번째 방법의 이점은 일부 메시지를 즉시 활성화 또는 비활성화 할 수 있다는 것입니다. 그러나 문제는 내가 EPiServer CMS에서 개발 중이며 log4net을 사용하는 자체 로깅 시스템이 있으며 루트 수준에서 정보 로깅을 활성화하면 많은 시스템 로그가 기록된다는 것입니다.

log4net을 어떻게 사용합니까? 시스템의 각 부분이 자체 로거에 기록하거나 모든 것이 기본 로거에 기록되고 구성이 다음에 수행 할 작업을 결정합니까?


코드 내에서 메시지를 기록하는 방법과 관련하여 두 번째 방법을 선택합니다.

ILog log = LogManager.GetLogger(typeof(Bar));
log.Info("message");

위의 로그로 전송 된 메시지는 완전한 형식을 사용하여 '이름이 지정'됩니다. Bar예 :

MyNamespace.Foo.Bar [INFO] message

이 접근 방식의 장점은 로깅을 구성하는 사실상의 표준이며 네임 스페이스별로 로그 메시지를 필터링 할 수 있다는 것입니다. 예를 들어 INFO 수준 메시지를 기록하도록 지정할 수 있지만 Bar특히 DEBUG에 대한 로깅 수준을 올릴 수 있습니다 .

<log4net>
    <!-- appenders go here -->
    <root>
        <level value="INFO" />
        <appender-ref ref="myLogAppender" />
    </root>

    <logger name="MyNamespace.Foo.Bar">
        <level value="DEBUG" />
    </logger>
</log4net>

이름을 통해 로깅을 필터링하는 기능은 log4net의 강력한 기능입니다. 모든 메시지를에 로깅하기 만하면이 기능의 대부분을 잃게됩니다 "myLog"!

EPiServer CMS와 관련하여 위의 접근 방식을 사용하여 CMS 및 자체 코드에 대해 다른 로깅 수준을 지정할 수 있어야합니다.

For further reading, here is a codeproject article I wrote on logging:


My Answer might be coming late, but I think it can help newbie. You shall not see logs executed unless the changes are made as below.

2 Files have to be changes when you implement Log4net.


  1. Add Reference of log4net.dll in the project.
  2. app.config
  3. Class file where you will implement Logs.

Inside [app.config] :

First, under 'configSections', you need to add below piece of code;

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

Then, under 'configuration' block, you need to write below piece of code.(This piece of code is customised as per my need , but it works like charm.)

<log4net debug="true">
    <logger name="log">
      <level value="All"></level>
      <appender-ref ref="RollingLogFileAppender" />
    </logger>

    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="1" />
      <maximumFileSize value="1MB" />
      <staticLogFileName value="true" />

      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %C.%M [%line] %-5level - %message %newline %exception %newline" />
      </layout>
    </appender>
</log4net>

Inside Calling Class :

Inside the class where you are going to use this log4net, you need to declare below piece of code.

 ILog log = LogManager.GetLogger("log");

Now, you are ready call log wherever you want in that same class. Below is one of the method you can call while doing operations.

log.Error("message");

Instead of naming my invoking class, I started using the following:

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

In this way, I can use the same line of code in every class that uses log4net without having to remember to change code when I copy and paste. Alternatively, i could create a logging class, and have every other class inherit from my logging class.


Disadvantage of second approach is big repository with created loggers. This loggers do the same if root is defined and class loggers are not defined. Standard scenario on production system is using few loggers dedicated to group of class. Sorry for my English.

참고URL : https://stackoverflow.com/questions/7089286/correct-way-of-using-log4net-logger-naming

반응형