简体   繁体   English

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

[英]How to use log4net in Asp.net core 2.0

I configure log4net in my asp.net core 2.0 application as mentioned in this article LINK我在我的 asp.net core 2.0 应用程序中配置了log4net ,如本文链接所述

program.cs程序.cs

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

    BuildWebHost(args).Run();
}

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.倒霉!我没有看到‪产生的任何文件C:\\Temp\\app.log目录。 What would be the mistake?会有什么错误? how to configure log4net for asp.net core 2.0?如何为asp.net core 2.0配置log4net

There is a third-party log4net adapter for the 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-plate code.因此,您不必编写任何样板代码。

More info here 更多信息在这里

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网站根目录中的 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>

Still looking for a solution?还在寻找解决方案吗? I got mine from this link .我从这个链接得到了我的。

All I had to do was add this two lines of code at the top of "public static void Main" method in the "program class".我所要做的就是在“程序类”中的“public static void Main”方法的顶部添加这两行代码。

 var logRepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
 XmlConfigurator.Configure(logRepo, new FileInfo("log4net.config"));

Yes, you have to add:是的,您必须添加:

  1. Microsoft.Extensions.Logging.Log4Net.AspNetCore using NuGet. Microsoft.Extensions.Logging.Log4Net.AspNetCore 使用 NuGet。
  2. A text file with the name of log4net.config and change the property(Copy to Output Directory) of the file to "Copy if Newer" or "Copy always".一个名为 log4net.config 的文本文件,并将文件的属性(复制到输出目录)更改为“如果较新则复制”或“始终复制”。

You can also configure your asp.net core application in such a way that everything that is logged in the output console will be logged in the appender of your choice.您还可以配置您的 asp.net 核心应用程序,以便在输出控制台中记录的所有内容都将记录在您选择的 appender 中。 You can also download this example code from github and see how i configured it.你也可以从github下载这个示例代码,看看我是如何配置它的。

You need to install the Microsoft.Extensions.Logging.Log4Net.AspNetCore NuGet package and add a log4net.config-file to your application.您需要安装Microsoft.Extensions.Logging.Log4Net.AspNetCore NuGet 包并将 log4net.config 文件添加到您的应用程序。 Then this should work:那么这应该工作:

public class Program
{
    private readonly ILogger<Program> logger;

    public Program()
    {
        var services = new ServiceCollection()
            .AddLogging(logBuilder => logBuilder.SetMinimumLevel(LogLevel.Debug))
            .BuildServiceProvider();


        logger = services.GetService<ILoggerFactory>()
            .AddLog4Net()
            .CreateLogger<Program>();
    }

    static void Main(string[] args)
    {
        Program program = new Program();

        program.Run();

        Console.WriteLine("\n\nPress any key to continue...");
        Console.ReadKey();
    }

    private void Run()
    {
        logger.LogInformation("Logging is working");
    }
}

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.按照 Irfan 的回答,我在 OSX 上使用 .NET Core 2.1.300 进行了以下 XML 配置,它可以正确记录并附加到./log文件夹和控制台。 Note the log4net.config must exist in the solution root (whereas in my case, my app root is a subfolder).请注意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 节点。

I've figured out what the issue is the namespace is ambigious in the loggerFactory.AddLog4Net().我已经发现问题是 loggerFactory.AddLog4Net() 中的命名空间不明确。 Here is a brief summary of how I added log4Net to my Asp.Net Core project.这是我如何将 log4Net 添加到我的 Asp.Net Core 项目的简要总结。

  1. Add the nugget package Microsoft.Extensions.Logging.Log4Net.AspNetCore添加金块包 Microsoft.Extensions.Logging.Log4Net.AspNetCore
  2. Add the log4net.config file in your root application folder在根应用程序文件夹中添加 log4net.config 文件

  3. Open the Startup.cs file and change the Configure method to add log4net support with this line loggerFactory.AddLog4Net打开 Startup.cs 文件并更改 Configure 方法以使用此行 loggerFactory.AddLog4Net 添加 log4net 支持

First you have to import the package using Microsoft.Extensions.Logging;首先,您必须使用 Microsoft.Extensions.Logging 导入包; using the using statement使用 using 语句

Here is the entire method, you have to prefix the ILoggerFactory interface with the namespace这是整个方法,您必须在 ILoggerFactory 接口前面加上命名空间

public void Configure(IApplicationBuilder app, IHostingEnvironment env, NorthwindContext context, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory)
        {
            loggerFactory.AddLog4Net();
            ....
        }

I was able to respond with the following methods:我能够用以下方法做出回应:

1-Install-Package log4net
2-Install-Package MicroKnights.Log4NetAdoNetAppender
3-Install-Package System.Data.SqlClient

First,I Create Database and Table with this Code:首先,我使用以下代码创建数据库和表:

CREATE DATABSE Log4netDb
CREATE TABLE [dbo].[Log] (
    [Id] [int] IDENTITY (1, 1) NOT NULL,
    [Date] [datetime] NOT NULL,
    [Thread] [varchar] (255) NOT NULL,
    [Level] [varchar] (50) NOT NULL,
    [Logger] [varchar] (255) NOT NULL,
    [Message] [varchar] (4000) NOT NULL,
    [Exception] [varchar] (2000) NULL
)

Second, I Create log4net.config File in program .其次,我在程序中创建 log4net.config 文件。 This is a simple configuration with no customization on the log message:这是一个简单的配置,没有对日志消息进行自定义:

<?xml version="1.0" encoding="utf-8" ?>
<log4net debug="true">
  <!-- definition of the RollingLogFileAppender goes here -->
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="Logs/WebApp.log" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="10MB" />
    <staticLogFileName value="true" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <layout type="log4net.Layout.PatternLayout">
      <!-- Format is [date/time] [log level] [thread] message-->
      <conversionPattern value="[%date] [%level] [%thread] %m%n" />
    </layout>
  </appender>
  <appender name="AdoNetAppender" type="MicroKnights.Logging.AdoNetAppender, MicroKnights.Log4NetAdoNetAppender">
    <bufferSize value="1" />
    <connectionType value="System.Data.SqlClient.SqlConnection, System.Data" />
    <connectionStringName value="log4net" />
    <connectionStringFile value="appsettings.json" />
    <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
    <parameter>
      <parameterName value="@log_date" />
      <dbType value="DateTime" />
      <layout type="log4net.Layout.RawTimeStampLayout" />
    </parameter>
    <parameter>
      <parameterName value="@thread" />
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%thread" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@log_level" />
      <dbType value="String" />
      <size value="50" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%level" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@logger" />
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%logger" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@message" />
      <dbType value="String" />
      <size value="4000" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@exception" />
      <dbType value="String" />
      <size value="2000" />
      <layout type="log4net.Layout.ExceptionLayout" />
    </parameter>
  </appender>
  <root>
    <level value="ALL" />
    <appender-ref ref="RollingLogFileAppender" />
    <appender-ref ref="AdoNetAppender" />
  </root>
</log4net>

Third, Replace code below with 'IHostBuilder' :第三,将下面的代码替换为 'IHostBuilder' :

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
    .ConfigureLogging(logging =>
    {
        // clear default logging providers
        logging.ClearProviders();
        logging.AddConsole();  
        logging.AddDebug();
        logging.AddEventLog();
        // add more providers here
    })
    .UseStartup<Startup>();

Fourth, in appsettings.json insert this code:四、在 appsettings.json 中插入这段代码:

{
  "connectionStrings": {
    "log4net": "Server=MICKO-PC;Database=Log4netDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

At the end, Use these commands to enjoy logging in最后,使用这些命令享受登录

public class ValuesController : Controller
{
    private static readonly ILog log = LogManager.GetLogger(typeof(ValuesController));
    
    [HttpPost]
    public async Task<IActionResult> Login(string userName, string password)
    {
        log.Info("Action start");
        
        // More code here ...
        log.Info("Action end");
    }
    
    // More code here...
} 

Good luck.祝你好运。

Click here to learn how to implement log4net in .NET Core 2.2单击此处了解如何在 .NET Core 2.2 中实现 log4net

The following steps are taken from the above link, and break down how to add log4net to a .NET Core 2.2 project.以下步骤取自上述链接,分解了如何将 log4net 添加到 .NET Core 2.2 项目。

First, run the following command in the Package-Manager console:首先,在包管理器控制台中运行以下命令:

Install-Package Log4Net_Logging -Version 1.0.0

Then add a log4net.config with the following information (please edit it to match your set up):然后添加具有以下信息的 log4net.config(请编辑它以匹配您的设置):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="logfile.log" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d [%t] %-5p - %m%n" />
      </layout>
    </appender>
    <root>
      <!--LogLevel: OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
      <level value="ALL" />
      <appender-ref ref="FileAppender" />
    </root>
  </log4net>
</configuration>

Then, add the following code into a controller (this is an example, please edit it before adding it to your controller):然后,将以下代码添加到控制器中(这是一个示例,请在将其添加到控制器之前对其进行编辑):

public ValuesController()
{
    LogFourNet.SetUp(Assembly.GetEntryAssembly(), "log4net.config");
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
    LogFourNet.Info(this, "This is Info logging");
    LogFourNet.Debug(this, "This is Debug logging");
    LogFourNet.Error(this, "This is Error logging");    
    return new string[] { "value1", "value2" };
}

Then call the relevant controller action (using the above example, call /Values/Get with an HTTP GET), and you will receive the output matching the following:然后调用相关的控制器操作(使用上面的示例,使用 HTTP GET 调用/Values/Get ),您将收到与以下内容匹配的输出:

2019-06-05 19:58:45,103 [9] INFO-[Log4NetLogging_Project.Controllers.ValuesController.Get:23] - This is Info logging 2019-06-05 19:58:45,103 [9] INFO-[Log4NetLogging_Project.Controllers.ValuesController.Get:23] - 这是信息记录

I am porting a .Net Framework console app to .Net Core and found a similar issue with log files not getting created under certain circumstances.我正在将 .Net Framework 控制台应用程序移植到 .Net Core,并发现在某些情况下未创建日志文件的类似问题。

When using " CreateRepository " there appears to be a difference between .net framework and .net standard.使用“ CreateRepository ”时,.net 框架和 .net 标准之间似乎存在差异。

Under .Net Framework this worked to create a unique Log instance with it's own filename using the same property from log4net.config在 .Net Framework下,这可以使用 log4net.config 中的相同属性创建一个具有自己文件名的唯一 Log 实例

GlobalContext.Properties["LogName"] = LogName;
var loggerRepository = LogManager.CreateRepository(LogName);
XmlConfigurator.Configure(loggerRepository);

Under .Net Standard this didn't work and if you turn on tracing you see it can't find the configuration file ".config".在 .Net Standard 下这不起作用,如果您打开跟踪,您会看到它找不到配置文件“.config”。 It wasn't loading the previous known configuration.它没有加载以前的已知配置。 Once I added the configuration to the configurator it still didn't log, while not complaining about it either.一旦我将配置添加到配置器,它仍然没有记录,同时也没有抱怨它。

To get it working under .Net Standard with similar behavior as before, this is what I did.为了让它在 .Net Standard 下以与以前类似的行为工作,这就是我所做的。

var loggerRepository = LogManager.CreateRepository(LogName);
XmlConfigurator.Configure(loggerRepository,new FileInfo("log4net.config"));
var hierarchy = (Hierarchy) loggerRepository;
var appender = (RollingFileAppender)hierarchy.Root.GetAppender("RollingLogFileAppender");
appender.File = Path.Combine(Directory.GetCurrentDirectory(), "logs", $"{LogName}.log");

I didn't want to create a configuration file for every repo, so this works.我不想为每个 repo 创建一个配置文件,所以这是有效的。 Perhaps there is a better way to get the .Net Framework behavior as before and if there is please let me know below.也许有更好的方法可以像以前一样获得 .Net Framework 行为,如果有,请在下面告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM