tjhack
tjhack

Reputation: 1032

log4net catch all controller action errors for web api

I am currently implementing log4net for catching my exceptions for web api controller.

I wanted to know how could i potentially catch all errors in any action within the controller?

I did not want to go through each action ideally and add try catch if it can be helped?

Upvotes: 0

Views: 1903

Answers (2)

Hasani Blackwell
Hasani Blackwell

Reputation: 2056

You need to register an IExceptionLogger

e.x.: GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new YourWebApiExceptionLogger());

Upvotes: 2

Peter
Peter

Reputation: 27944

You can implement a System.Web.Http.Filters.ActionFilterAttribute. In the OnActionExecuted you can handle your logging:

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
            if (actionExecutedContext.Response != null)
            {
              //ok
            }
            else
            {
                _logger.ErrorFormat("actionExecutedContext.Response == null will result in 500, unhandled exception"); //Add extra information here
            }
    }

Then you can add this ActionFilter as attribute to the methods you want to log.

Upvotes: 1

Related Questions