Geeks With Blogs

News
AngelEyes on .Net Tips, tricks and WTFs about Asp .Net, SQL Server and the likes.
Just found out - very easily - a simple way to add logging (via log4net) to my .Net Web API. Thanks to a "code friendly" post.

The whole article is full of useful information, though in this instance I focused on global logging alone.

This was accomplished (again, easily) by adding the following to global.asax.cs at app-start or a function called from it:

GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger());

And adding the class itself:

    internal class GlobalExceptionLogger : ExceptionLogger
    {
        private static readonly ILog Log4Net = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public override void Log(ExceptionLoggerContext context)
        {
            Log4Net.Error(String.Format("Unhandled exception thrown in {0} for request {1}: {2}",
                                        context.Request.Method, context.Request.RequestUri, context.Exception));
        }
    }
Posted on Tuesday, March 10, 2015 10:24 AM | Back to top


Comments on this post: WebAPI Exception Logging

# re: WebAPI Exception Logging
Requesting Gravatar...
Thanks for sharing like this.
Left by cute angel on Mar 10, 2015 9:24 PM

Your comment:
 (will show your gravatar)


Copyright © AngelEyes | Powered by: GeeksWithBlogs.net