如何使用 asp.net web api 应用程序中的 log4net.elmah.io 包在 elmah.io 中设置 URL、状态代码和版本等参数?

How to set parameters like URL, Status Codes and Version in elmah.io using log4net.elmah.io package in asp.net web api application?

我正在使用 log4net.elmah.io 进行日志记录。

这是我的 lo4net.config 文件

<configuration>
 <configSections>
    <section name="log4net" type ="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
 </configSections>
 <log4net>
    <appender name="ElmahIoAppender" type="elmah.io.log4net.ElmahIoAppender, elmah.io.log4net">
      <logId value="LOG_ID" />
      <apiKey value="API_KEY" />
    </appender>
    <root>
      <level value="debug"/>
      <appender-ref ref="RollingFileAppender"/>
      <appender-ref ref="ElmahIoAppender" />
    </root>
  </log4net>
</configuration>

我创建了一个名为 MyFilterAttribute

的用于记录目的的 class
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace Resume
{
    public class MyFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.Request.Method == HttpMethod.Get)
            {
                var log = log4net.LogManager.GetLogger(typeof(ApiController));
                log.Info("This is log meassage for GET method");
            }

        }
    }
}

MyFilterAttribute在controller中的action方法之前提到如下:

[Route("api/employees/{id}")]
[HttpGet]
[MyFilterAttribute]
public HttpResponseMessage GetEmployee(int id)
 {
    var employee = _unitOfWork.Employee.Get(id);

    return employee != null? Request.CreateResponse(HttpStatusCode.OK, employee) : Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee with Id " + id + " does not exist");
}

发出请求后,我能够收到响应和日志消息。

elmah.io中的输出图像如下: https://ibb.co/QrFBQdx

elmah.io

的输出请看图片的URL

您可以看到 URL 状态代码未被记录。

哪位大侠帮忙解决一下

您可以将以下代码放在 Global.asax.cs 中的 Application_Start 方法中:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        ...

        Hierarchy hier = log4net.LogManager.GetRepository() as Hierarchy;
        var elmahIoAppender = (ElmahIoAppender)(hier?.GetAppenders())
            .FirstOrDefault(appender => appender.Name
                .Equals("ElmahIoAppender", StringComparison.InvariantCultureIgnoreCase));

        elmahIoAppender.ActivateOptions();
        elmahIoAppender.Client.Messages.OnMessage += (sender, a) =>
        {
            var ctx = HttpContext.Current;
            if (ctx == null) return;
            a.Message.Url = ctx.Request?.Path;
            a.Message.StatusCode = ctx.Response?.StatusCode;
        };
    }
}

这将导致为每个日志消息触发 OnMessage 回调。如果记录时有 HTTP 上下文,UrlStatusCode 字段将填写在记录到 elmah.io.

的消息中