我正在尝试在WebApi 2.2上构建的OData v4服务中记录异常。我正在使用NLog进行日志记录。为此,我创建了一个简单的ExceptionLogger(NLogExceptionLogger)类。 NLogExceptionLogger会记录未处理的异常,但不会记录所有异常。如果我手动抛出异常作为测试它可以正常工作。 (参见控制器示例)
我正在寻找的具体是在验证ODataQuery时抛出的Microsoft.OData.ODataExceptions。错误信息在响应中返回,但不会被NLogExceptionLogger记录。基本上对于尝试$ expand的查询或$ select未启用的字段,我希望在日志中看到这些例外。
我的假设是ExceptionLogger只能看到未处理的异常,这些异常对我所希望的帮助不大。有没有办法可以记录这些例外?
NLogExceptionLogger:
public class NLogExceptionLogger : ExceptionLogger
{
public override void Log(ExceptionLoggerContext context)
{
string loggerName;
try
{
loggerName = context.ExceptionContext.ControllerContext.ControllerDescriptor.ControllerType.FullName;
}
catch (Exception)
{
loggerName = "NLogExceptionLogger";
}
NLog.Logger logger = NLog.LogManager.GetLogger(loggerName);
logger.Error(context.Exception, "Exception");
}
}
WebApiConfig.cs片段:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Add global exception logger
config.Services.Replace(typeof(IExceptionLogger), new NLogExceptionLogger());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Customer>("Customers");
builder.EntityType<Customer>().Filter("Name");
[[[ The rest of ODataConventionModelBuilder removed for brevity ]]]
config.MapODataServiceRoute("MainODataRoute", "data", builder.GetEdmModel());
}
控制器示例:
[System.Web.Http.Description.ApiExplorerSettings(IgnoreApi = false)]
public class CustomersController : ODataController
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
CustomerDB db = new CustomerDB();
/// <summary>
/// Customers
/// </summary>
[EnableQuery]
public IQueryable<Customer> Get()
{
logger.Debug("Customer Get Test");
//throw new Exception("BOO!");
return db.Customers;
}
... etc