我使用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的类
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,如下所示:
[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和状态代码未被记录。
谁来帮我解决这个问题。
发布于 2019-08-21 18:45:19
您可以将以下代码放入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上下文,则会在记录到elmah.io的消息上填充Url和StatusCode字段。
https://stackoverflow.com/questions/57586988
复制相似问题