如何将事件记录到 ASP.NET Core Web API 中的事件查看器? [英] How can I log events to the Event Viewer in an ASP.NET Core Web API?

查看:24
本文介绍了如何将事件记录到 ASP.NET Core Web API 中的事件查看器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试登录到托管在 Windows Server 2016 Standard 上的 ASP.NET Core 2.1 Web API 中的事件查看器.

I'm trying to log to the Event Viewer in an ASP.NET Core 2.1 Web API, hosted on Windows Server 2016 Standard.

我的控制器中有这个:

private readonly ILogger<MyController> _logger;
private readonly MyContext _context;

public TestController(MyContext context, ILogger<MyController> logger)
{
    _context = context;
    _logger = logger;
}

但我认为我在 Program.cs 中的 CreateWebHostBuilder() 方法中做错了什么,因为它不起作用:

But I think I'm doing something wrong in my CreateWebHostBuilder() method in Program.cs because it's not working:

我有这个:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();

然后我将其修改为:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddEventSourceLogger();
            });

但我一定是做错了什么...有什么想法吗?我在这里读到,显然 EVent Viewer 日志记录现在已融入 .Net Core 2.1 Write to EventLog in.Net 核心

But I must be doing something wrong... Any ideas? I read here that apparently EVent Viewer logging is now baked into .Net Core 2.1 Write to EventLog in .Net Core

推荐答案

对于使用 .NET Core 2.2 偶然发现此问题的任何人,事件日志记录器(来自 Microsoft.Extensions.Logging.EventLog)现在应该在 Program.cs 中添加:

For anyone who stumbles upon this using .NET Core 2.2, the Event Log logger (from Microsoft.Extensions.Logging.EventLog) should now be added in the Program.cs:

public static void Main(string[] args)
{
    CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging((context, logging) =>
        {
            logging.AddEventLog();
        })
        .UseStartup<Startup>();

这在 .NET Core 日志记录文档.

更新:如果有人在 .NET Core 2.2 发布后仍然登陆这里,这仍然与 .NET Core 3.1 日志记录.

UPDATE: In case someone still lands here post .NET Core 2.2, this is still relevant for .NET Core 3.1 logging.

这篇关于如何将事件记录到 ASP.NET Core Web API 中的事件查看器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆