开发者

mvc logging: [LogRequest] vs OnActionExecuting

开发者 https://www.devze.com 2023-04-09 03:33 出处:网络
i\'m a .net/c# noob (long-time servlet/java developer) i need to add logging to my mvc application. i want it to be fairly cheap performance-wise, and simple to configure.

i'm a .net/c# noob (long-time servlet/java developer)

i need to add logging to my mvc application. i want it to be fairly cheap performance-wise, and simple to configure.

what i would initially like to do is log each incoming controller action. it occurred to me that there might be a single-point-of-entry so i don't have to add a line of code to every controller's action methods.

the way i see it, i can either add a [LogRequest] attribute to the controller (in my case, a base controller) and then implement a

public class LogsRequestsAttribute : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    { ... }
}

class to handle the logrequest attribute.

or

i could just override the base controller as per:

public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
       // perform some action here
    }
}

and inherit all my controllers from BaseController.

in terms of performance, which would be quicker?


also, in terms of performance, i am considering putting the actual logging method call in a non-blocking thread that runs once and dies. any pitfalls with this approach? the goal is to let the app proceed and not wait around for the logging method to finish i开发者_Python百科t's task.


If you're using MVC3, I'd recommend adding your action filter to the global filters collection rather than requiring a base controller. At app startup, in your Global.asax ("MvcApplication") class, you'll need a line like:

GlobalFilters.Filters.Add(new LogRequestsAttribute());

That will run it for all controller actions.

From a performance perspective, I don't think you'll see much difference between the attribute or the base controller mechanism. I've not tried it, but since the action filter portion of the MVC pipeline is going to run regardless of you having a base controller, the real consideration here would be flexibility rather than performance. The more flexible design is to isolate the logging from the controller.

I'd look at using a third-party log solution like log4net, which is already optimized for speed and well-tested. That will allow you to avoid having to spin up asynchronous logging threads and all that. Just log to log4net in your action filter and call it good. That also allows you to do the async portion of things on a per-appender basis - more control. If you need async logging, write your log4net appender to be asynchronous rather than wrapping all the various logging calls with async behavior.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号