Logging in Asp.net MVC application using log4net

shoab picture shoab · Aug 27, 2013 · Viewed 11.2k times · Source

Mine is a Asp.net MVC 4 application. I need to implement the following; As per log level set in web.config file (eg. 1/2/3/4)

I have to log:

1 :

  • Methods start
  • Methods end
  • Application Warning

Application Exception

2:

  • Application Warnings
  • Application Exceptions

3:

  • Application Exceptions

4:

  • None

Further I need to achieve this using global filter(s).

kindly provide me some pointers.

Thanks in advance.


Resolved

Following are my steps

I created the following Filter class

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class LoggerFilterAttribute : ActionFilterAttribute
    {
        private ILog _objLog4Net = null;
        string logLevel = string.Empty;
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _objLog4Net = LogManager.GetLogger(filterContext.RouteData.Values["controller"].ToString());
            logLevel = GetLogLevel();
            if (logLevel == "1")
            {
                _objLog4Net.Debug(string.Concat("Entered ", filterContext.Controller.GetType().ToString(), "'s ", filterContext.ActionDescriptor.ActionName, " method"));
            }
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            _objLog4Net = LogManager.GetLogger(filterContext.RouteData.Values["controller"].ToString());
            logLevel = GetLogLevel();
            if (logLevel == "1")
            {
                _objLog4Net.Debug(string.Concat("Existing ", filterContext.Controller.GetType().ToString(), "'s ", filterContext.ActionDescriptor.ActionName, " method"));
            }
        }

        private string GetLogLevel()
        {
            return ConfigurationManager.AppSettings["LOGLEVEL"].ToLower().ToString();
        }

    }

This class will check for loglevel in configuration file if found 1 Through OnActionExecuting() and OnActionExecuted() Will log for Method Start and Method End.

Further following is the ExceptionFilter class for logging exception

public class ExceptionFilterAttribute : HandleErrorAttribute
{
    private ILog _objLog4Net = null;
    string logLevel = string.Empty;
    public override void OnException(ExceptionContext filterContext)
    {

        _objLog4Net = LogManager.GetLogger(filterContext.RouteData.Values["controller"].ToString());

        logLevel = GetLogLevel();
        if (logLevel == "1" || logLevel == "2")
        {
            _objLog4Net.Error(filterContext.Exception.Message, filterContext.Exception);
        }

        if (logLevel == "3")
        {
            if (filterContext.Exception.GetType().IsSubclassOf(typeof(ApplicationException)))
            {
                _objLog4Net.Error(filterContext.Exception.Message, filterContext.Exception);
            }
        }
    }

    private string GetLogLevel()
    {
        return ConfigurationManager.AppSettings["LOGLEVEL1"].ToLower().ToString();
    }

}

This class as per log level, Logs All Exceptions or only Application exceptions.

If Loglevel is none no conditions get true / nothing is logged.

Answer

SBirthare picture SBirthare · Aug 27, 2013

These type of question are down voted that you will see soon... if you wonder here is why, you shared your requirement that might be unique however you did not shared the analysis effort you have spent. Due to which the question you asked falls in general category. I recognize being a new memeber on this site, it takes sometime to get this. So a little help from my side is,

  1. Go to below mentioned websites (search in google and you will get many more).
  2. Understand what log4net offers and how it works.
  3. Determine if it suits your requirement (if that option is open).
  4. Do a Proof-Of-Concept (POC), a sample project where you try out new stuff (for the person who is trying it first time) like log4net.
  5. Once you understand and start using the library post the specific questions or problem you face (we will be happy to help).

Few links are:

http://www.codeproject.com/Articles/140911/log4net-Tutorial http://www.eyecatch.no/blog/2012/08/logging-with-log4net-in-c-sharp/

Check below answer on SO as well: https://stackoverflow.com/questions/4670916/does-anyone-know-any-tutorial-preferably-book-on-log4net