Development Tip

log4net은이 로그 파일을 어디에 생성합니까?

yourdevel 2020. 11. 7. 10:35
반응형

log4net은이 로그 파일을 어디에 생성합니까?


파일 값을로 설정하면 logs\log-file.txt정확히 어디에이 폴더가 생성됩니까? 에서 /bin디렉토리?

내 web.config는 다음과 같습니다.

<log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="logs\log-file.txt" />
      <appendToFile value="true" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
</log4net>

이것이 올바른 로그 방법입니까?

ILog logger = LogManager.GetLogger(typeof(CCController));
logger.Error("Some Page", ex);  // where ex is the exception instance

로그 파일이 런타임에 결정될 지정된 위치에 배치되도록하려면 프로젝트 출력 디렉토리가 될 수 있습니다. 그런 다음 .config그런 방식으로 파일 항목을 구성 할 수 있습니다.

<file type="log4net.Util.PatternString" value="%property{LogFileName}.txt" />

호출하기 전에 코드에서 log4net configure아래와 같이 새 경로를 설정하십시오.

 log4net.GlobalContext.Properties["LogFileName"] = @"E:\\file1"; //log file path
 log4net.Config.XmlConfigurator.Configure();

얼마나 간단합니까? :)


프로젝트 / 솔루션의 루트 디렉토리에 파일이 생성됩니다.

다음과 같이 앱의 web.config에서 선택한 위치를 지정할 수 있습니다.

   <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="c:/ServiceLogs/Olympus.Core.log" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value=".yyyyMMdd.log" />
      <maximumFileSize value="5MB" />
      <staticLogFileName value="true" />
      <lockingModel type="log4net.Appender.RollingFileAppender+MinimalLock" />
      <maxSizeRollBackups value="-1" />
      <countDirection value="1" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %-5level [%thread] %logger - %message%newline%exception" />
      </layout>
    </appender>

파일 태그는 위치를 지정합니다.


파일 값은 "c : \ logs \ log.txt"와 같은 절대 경로이거나 bin 디렉토리에 상대적인 상대 경로 일 수 있습니다.

이를 구현하는 한 일반적으로 로그인하려는 모든 수업의 맨 위에 다음을 배치합니다.

private static readonly ILog Log = LogManager.GetLogger( 
MethodBase.GetCurrentMethod().DeclaringType);

마지막으로 다음과 같이 사용할 수 있습니다.

Log.Debug("This is a DEBUG level message.");

Log4net이 프로젝트 폴더에 저장 중입니다. 같은 것 : \SolutionFolder\ProjectFolder\bin\SolutionConfiguration\logs\log-file.txt.

어디:

  • SolutionFolder는 솔루션을 저장하는 곳입니다.
  • ProjectFolder는 프로젝트가 솔루션에 상주하는 폴더이며
  • SolutionConfiguration은 프로젝트의 모든 바이너리를 포함하는 폴더입니다 (기본값은 Debug 또는 Release 임).

도움이 되었기를 바랍니다!


FileAppender appender = repository.GetAppenders().OfType<FileAppender>().FirstOrDefault();
if (appender != null)
    logger.DebugFormat("log file located at : {0}", appender.File);
else
    logger.Error("Could not locate fileAppender");

로그 폴더 및 파일 항목의 경우 @Bens 답변으로 이동하십시오 .

I will comment on the creating log part, though. Imo there is no correct way. When coding loggers manually I do it the way you're doing it:

ILog logger = LogManager.GetLogger(typeof(CCController));

because it is short and concise.

That said, I do not create the logger instances inside the classes these days, I let my IoC container inject it for me.


I think your sample is saving to your project folders and unless the default iis, or .NET , user has create permission then it won't be able to create the logs folder.

I'd create the logs folder first and allow the iis user full permission and see if the log file is being created.


if you want to choose dynamically the path to the log file use the method written in this link: method to dynamic choose the log file path.

if you want you can set the path to where your app EXE file exists like this -

var logFileLocation = System.IO.Path.GetDirectoryName
(System.Reflection.Assembly.GetEntryAssembly().Location);

and then send this 'logFileLocation' to the method written in the link above like this:

Initialize(logFileLocation);

and you are ready to go! :)


I was developing for .NET core 2.1 using log4net 2.0.8 and found NealWalters code moans about 0 arguments for XmlConfigurator.Configure(). I found a solution by Matt Watson here

        log4net.GlobalContext.Properties["LogFileName"] = @"E:\\file1"; //log file path
        var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
        XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

참고URL : https://stackoverflow.com/questions/2815940/where-will-log4net-create-this-log-file

반응형