写入.Net Core中的EventLog

时间:2016-08-24 19:05:13

标签: c# logging .net-core dnx

我需要一种在我的应用程序中使用dnx写入Windows事件查看器的方法。但是,EventLog类在System.Diagnostics命名空间中不可用,所以我被卡住了。有没有其他方法可以写入EventViewer?

4 个答案:

答案 0 :(得分:6)

要写入.Net Core中的事件日志,首先需要安装Nuget软件包

Install-Package Microsoft.Extensions.Logging.EventLog -Version 3.1.2

请注意,要安装的正确版本取决于您所运行的.Net Core的版本。上面的程序包已通过.Net Core进行了测试。

然后,我们需要添加EventLog。在Program类中,我们可以这样做:

    using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.EventLog;

namespace SomeAcme.SomeApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging((hostingContext, logging) =>
                {
                    logging.ClearProviders();
                    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                    logging.AddEventLog(new EventLogSettings()
                    {
                        **SourceName = "SomeApi",
                        LogName = "SomeApi",**
                        Filter = (x, y) => y >= LogLevel.Warning
                    });
                    logging.AddConsole();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

我们的appsettings.json文件包括设置:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.\\SQLEXPRESS;Database=SomeApi;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  **"Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },**
  "AllowedHosts": "*"
}

我们可以注入ILogger实例

using SomeAcme.SomeApi.SomeModels;
using SomeAcme.SomeApi.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;

namespace SomeAcme.SomeApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SomeController : ControllerBase
    {
        private readonly ISomeService _healthUnitService;
        private readonly ILogger<SomeController> _logger;

        public SomeController(ISomeService someService, ILogger<SomeController> logger)
        {
            _someService= someService;
            _logger = logger;
        }
        // GET: api/Some
        [HttpGet]
        public IEnumerable<SomeModel> GetAll()
        {
            return _someService.GetAll();
        }
    }
}

更多高级用法,请在.Net Core中的Startup类的Configure方法内添加全局异常处理程序:

  //Set up a global error handler for handling Unhandled exceptions in the API by logging it and giving a HTTP 500 Error with diagnostic information in Development and Staging
        app.UseExceptionHandler(errorApp =>
        {
            errorApp.Run(async context =>
            {
                context.Response.StatusCode = 500; // or another Status accordingly to Exception Type
                context.Response.ContentType = "application/json";

                var status = context.Features.Get<IStatusCodeReExecuteFeature>();

                var error = context.Features.Get<IExceptionHandlerFeature>();
                if (error != null)
                {
                    var ex = error.Error;
                    string exTitle = "Http 500 Internal Server Error in SomeAcme.SomeApi occured. The unhandled error is: ";
                    string exceptionString = !env.IsProduction() ? (new ExceptionModel
                    {
                        Message = exTitle + ex.Message,
                        InnerException = ex?.InnerException?.Message,
                        StackTrace = ex?.StackTrace,
                        OccuredAt = DateTime.Now,
                        QueryStringOfException = status?.OriginalQueryString,
                        RouteOfException = status?.OriginalPath
                    }).ToString() : new ExceptionModel()
                    {
                        Message = exTitle + ex.Message,
                        OccuredAt = DateTime.Now
                    }.ToString();
                    try
                    {
                        _logger.LogError(exceptionString);
                    }
                    catch (Exception err)
                    {
                        Console.WriteLine(err);
                    }
                    await context.Response.WriteAsync(exceptionString, Encoding.UTF8);
                }
            });
        });

最后是一个帮助程序模型,用于将我们的异常信息打包到其中。

using System;
using Newtonsoft.Json;

namespace SomeAcme.SomeApi.Models
{
    /// <summary>
    /// Exception model for generic useful information to be returned to client caller
    /// </summary>
    public class ExceptionModel
    {
        public string Message { get; set; }
        public string InnerException { get; set; }
        public DateTime OccuredAt { get; set; }
        public string StackTrace { get; set; }
        public string RouteOfException { get; set; }
        public string QueryStringOfException { get; set; }

        public override string ToString()
        {
            return JsonConvert.SerializeObject(this);
        }
    }
}

这里的棘手之处在于掌握Startup类中的记录器。 您可以为此注入ILoggerFactory并这样做:

  _logger = loggerFactory.CreateLogger<Startup>();

在上面的全局错误处理程序中使用_logger的地方。

现在再次回到如何写入事件日志的问题,查看上面的 SomeController 的源代码。我们在这里注入ILogger。 只需使用该实例,它就提供了不同的方法来写入配置的日志。由于我们已在Program类事件日志中添加了内容,因此这会自动发生。

在测试上面的代码之前,请以管理员身份运行以下Powershell脚本以获取事件日志源:

New-EventLog -LogName SomeApi -SourceName SomeApi

我喜欢这种方法的地方是,如果我们做的所有事情都正确无误,那么异常会很好地弹出到SomeApi源代码中,而不会弹出到应用程序事件日志中(麻烦的恕我直言)。

答案 1 :(得分:1)

答案 2 :(得分:1)

从NuGet Microsoft.Extensions.Logging.EventLog-版本2.1.1添加

CM>安装软件包Microsoft.Extensions.Logging.EventLog-版本2.1.1

在program.cs文件中包含名称空间Microsoft.Extensions.Logging.EventLog

这解决了我的问题。

答案 3 :(得分:0)

好消息! EventLog已经ported to corefx,将在.NET Core 2.1中提供。

现在您可以从他们的MyGet Feed下载预览包System.Diagnostics.EventLog。