【问题标题】:Where can I put Logging mechanism on my code我在哪里可以在我的代码上放置日志记录机制
【发布时间】:2017-07-19 12:36:52
【问题描述】:

我正在使用 asp.net mvc 应用程序,我对横切关注点不熟悉。所以我需要知道我可以在哪里使用我的记录器代码下面的例子。

我有一个记录错误的界面。我正在我的代码上实现这个接口。

public interface ILogger { void Log(Exception exception); }

所以我有 Controller、ProductService、ProductRepository 类。

public interface ProductController: ApiController{

     public IHttpActionResult Get(){
            try {
                productService.GetProducts();
            }catch(Exception e){
                logger.Log(e); // 1-Should I use logging in here?
            }
     }
} 

产品服务;

public class ProductService{
    public IEnumerable<Product> GetProducts(){
            try {
                productRepository.GetAll();
            }catch(Exception e){
                logger.Log(e); // 2-Should I use logging in here?
            }
    }   
}

在存储库中。

public class ProductRepository{
    public IEnumerable<Product> GetAll(){
            try {

            }catch(Exception e){
                logger.Log(e); // 3-Should I use logging in here?
            }
    }   
}

我无法确定在哪里可以使用日志记录代码。或者在任何地方添加登录。

【问题讨论】:

  • 您应该使用 MVC 3 层架构。您必须从控制器调用服务,该服务将引用应该负责记录的存储库。

标签: asp.net logging design-patterns asp.net-web-api


【解决方案1】:

您可以实现自定义异常过滤器。

public class LogExceptionAttribute : ExceptionFilterAttribute
{
    public ILogger logger { get; set; }
    public LogExceptionAttribute(ILogger logger)
    {
        this.logger = logger;
    }

    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        var exception = actionExecutedContext.Exception;
        logger.Log(actionExecutedContext.Exception);

        // You could also send client a message about exception.
        actionExecutedContext.Response =
                actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, exception.Message);
    }
}

然后在全局级别注册它。

GlobalConfiguration.Configuration.Filters.Add(new LogExceptionAttribute(Logger));

对于从控制器方法抛出的任何未处理的异常都会调用此过滤器。

【讨论】:

  • 所以如果服务或存储库实现发生异常,我会在ExceptionFilter中捕获。但我会向用户返回一条关于异常的用户友好消息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-07
  • 2015-09-23
  • 1970-01-01
  • 2021-08-31
  • 2018-08-12
  • 2019-01-22
相关资源
最近更新 更多