Log to Event Viewer in an ASP .Net Core 2.1 Web API

我是研究僧i 提交于 2019-12-11 02:52:56

问题


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

I've got this in my controller:

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

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

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

I had this:

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

and I modified it to this:

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

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


回答1:


Ok, I had to add Microsoft.Extensions.Logging.EventLog to the project (from Nuget).

Then, in Startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
   loggerFactory.AddEventLog();
}



回答2:


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>();

This is noted at the bottom of the .NET Core Logging docs.



来源:https://stackoverflow.com/questions/52310072/log-to-event-viewer-in-an-asp-net-core-2-1-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!