我正在尝试在基于 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