如何在Asp.net core 2.0中使用log4net

时间:2021-10-29 03:41:54

I configure log4net in my asp.net core 2.0 application as mentioned in this article LINK

我在我的asp.net core 2.0应用程序中配置log4net,如本文LINK中所述

program.cs

Program.cs中

public static void Main(string[] args)
{
    var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
    XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

    BuildWebHost(args).Run();
}

HomeController

HomeController的

public class HomeController : Controller
{
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(HomeController));

    public IActionResult Error()
    {
        log.Info("Hello logging world!");
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

log4net.config

log4net.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="RollingFile" />
    </root>
    <appender name="RollingFile" type="log4net.Appender.FileAppender">
      <file value="‪C:\Temp\app.log" /> 
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5p %d{hh:mm:ss} %message%newline" />
      </layout>
    </appender>
  </log4net>
</configuration>

Unlucky!, I didn't see any file generated in ‪C:\Temp\app.log directory. What would be the mistake? how to configure log4net for asp.net core 2.0?

不走运!,我没有看到在C:\ Temp \ app.log目录中生成任何文件。那会是什么错误?如何为asp.net core 2.0配置log4net?

4 个解决方案

#1


19  

I am successfully able to log a file using the following code

我成功地使用以下代码记录文件

public static void Main(string[] args)
{
    XmlDocument log4netConfig = new XmlDocument();
    log4netConfig.Load(File.OpenRead("log4net.config"));
    var repo = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(),
               typeof(log4net.Repository.Hierarchy.Hierarchy));
    log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);

    BuildWebHost(args).Run();
}

log4net.config in website root

网站root中的log4net.config

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="C:\Temp\" />
    <datePattern value="yyyy-MM-dd.'txt'"/>
    <staticLogFileName value="false"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level App  %newline %message %newline %newline"/>
    </layout>
  </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>
</log4net>

#2


4  

Note there is already log4net adapter for ASP.NET Core logging interface.

请注意,已有用于ASP.NET Core日志记录界面的log4net适配器。

Only thing you need to do is pass the ILoggerFactory to your Startup class, then call

您需要做的只是将ILoggerFactory传递给Startup类,然后调用

loggerFactory.AddLog4Net();

and have a config in place. So you don't have to write any boiler plating code.

并有一个配置到位。所以你不必写任何锅炉电镀代码。

https://github.com/huorswords/Microsoft.Extensions.Logging.Log4Net.AspNetCore

https://github.com/huorswords/Microsoft.Extensions.Logging.Log4Net.AspNetCore

#3


0  

Following on Irfan's answer, I have the following XML configuration on OSX with .NET Core 2.1.300 which correctly logs and appends to a ./log folder and also to the console. Note the log4net.config must exist in the solution root (whereas in my case, my app root is a subfolder).

根据Irfan的回答,我在OSX上使用.NET Core 2.1.300进行了以下XML配置,它正确地记录并附加到./log文件夹和控制台。请注意,log4net.config必须存在于解决方案根目录中(而在我的情况下,我的应用程序根目录是一个子文件夹)。

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %-5level %logger - %message%newline" />
      </layout>
  </appender>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="logs/" />
    <datePattern value="yyyy-MM-dd.'txt'"/>
    <staticLogFileName value="false"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level App  %newline %message %newline %newline"/>
    </layout>
  </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingLogFileAppender"/>
      <appender-ref ref="ConsoleAppender"/>
    </root>
</log4net>

Another note, the traditional way of setting the XML up within app.config did not work:

另一个注意事项,在app.config中设置XML的传统方法不起作用:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net> ...

For some reason, the log4net node was not found when accessing the XMLDocument via log4netConfig["log4net"].

出于某种原因,通过log4netConfig [“log4net”]访问XMLDocument时找不到log4net节点。

#4


-1  

Sorry for the delay!

抱歉耽搁了!

In my scenario, it's all about .config schema. above one was created with .config extend simply so it troubles me. If I would have created the config file through schema above the code works perfect.

在我的场景中,它是关于.config架构的。上面的一个是用.config扩展创建的,所以它让我很烦恼。如果我通过上面的模式创建了配置文件,那么代码就可以完美运行。

#1


19  

I am successfully able to log a file using the following code

我成功地使用以下代码记录文件

public static void Main(string[] args)
{
    XmlDocument log4netConfig = new XmlDocument();
    log4netConfig.Load(File.OpenRead("log4net.config"));
    var repo = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(),
               typeof(log4net.Repository.Hierarchy.Hierarchy));
    log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);

    BuildWebHost(args).Run();
}

log4net.config in website root

网站root中的log4net.config

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="C:\Temp\" />
    <datePattern value="yyyy-MM-dd.'txt'"/>
    <staticLogFileName value="false"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level App  %newline %message %newline %newline"/>
    </layout>
  </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>
</log4net>

#2


4  

Note there is already log4net adapter for ASP.NET Core logging interface.

请注意,已有用于ASP.NET Core日志记录界面的log4net适配器。

Only thing you need to do is pass the ILoggerFactory to your Startup class, then call

您需要做的只是将ILoggerFactory传递给Startup类,然后调用

loggerFactory.AddLog4Net();

and have a config in place. So you don't have to write any boiler plating code.

并有一个配置到位。所以你不必写任何锅炉电镀代码。

https://github.com/huorswords/Microsoft.Extensions.Logging.Log4Net.AspNetCore

https://github.com/huorswords/Microsoft.Extensions.Logging.Log4Net.AspNetCore

#3


0  

Following on Irfan's answer, I have the following XML configuration on OSX with .NET Core 2.1.300 which correctly logs and appends to a ./log folder and also to the console. Note the log4net.config must exist in the solution root (whereas in my case, my app root is a subfolder).

根据Irfan的回答,我在OSX上使用.NET Core 2.1.300进行了以下XML配置,它正确地记录并附加到./log文件夹和控制台。请注意,log4net.config必须存在于解决方案根目录中(而在我的情况下,我的应用程序根目录是一个子文件夹)。

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %-5level %logger - %message%newline" />
      </layout>
  </appender>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="logs/" />
    <datePattern value="yyyy-MM-dd.'txt'"/>
    <staticLogFileName value="false"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level App  %newline %message %newline %newline"/>
    </layout>
  </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingLogFileAppender"/>
      <appender-ref ref="ConsoleAppender"/>
    </root>
</log4net>

Another note, the traditional way of setting the XML up within app.config did not work:

另一个注意事项,在app.config中设置XML的传统方法不起作用:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net> ...

For some reason, the log4net node was not found when accessing the XMLDocument via log4netConfig["log4net"].

出于某种原因,通过log4netConfig [“log4net”]访问XMLDocument时找不到log4net节点。

#4


-1  

Sorry for the delay!

抱歉耽搁了!

In my scenario, it's all about .config schema. above one was created with .config extend simply so it troubles me. If I would have created the config file through schema above the code works perfect.

在我的场景中,它是关于.config架构的。上面的一个是用.config扩展创建的,所以它让我很烦恼。如果我通过上面的模式创建了配置文件,那么代码就可以完美运行。