Search code examples
c#asp.netlog4neterror-logging

Using log4net with asp.net web forms


I am trying to incorporate log4net into my web application. I have already done so with the newer portion based on .net mvc, but am having trouble incorporating it into the web forms based portion of my app. I have looked around for an example and have not come across one.

In order to narrow my question down, let's assume I know how to configure my web.config file. My questions are:

(1) I have considered placing the actual call to log4net in a "Global.asax" file as well as placing it in my base page (on which all other pages are built). Should I be placing the actual code in either of these places, and if not where should I put the code?

(2) My understanding of the code is that I need to instantiate a log, and then have that log log stuff when I want to it (the specifics of log being taken care of by web.config), but I don't know what that code should actually look like. So, what code should I actually be placing in my file? (example would be appreciated)

Thanks


Solution

  • just place the code where you need it.

    to initiate i just use this line in every page i need it...

    static Logger log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    

    so the logger gets the name of the current class including full namespace. i also use the logger in global.asax for example error logging

    protected void Application_Error(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("Unhandled error occured in application. Sender: ");
            sb.AppendLine(Request.RawUrl);
            sb.Append("Query: ");
            sb.AppendLine(Request.QueryString.ToString());
    
            Exception ex = Server.GetLastError().GetBaseException();
    
            log.Error(sb.ToString(), ex);
            Server.ClearError();
    
            Response.Redirect("~/Error.aspx");
        }
    

    but i seperate the log config from the web.config. it's easier for me and you don't have to handle so big files. i also think that the application is not restartet, when you change the log config file. if you update the web.config the application is always restartet as far as i know.

    to accomplish this you just need to add following to the web.config in add

    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
    

    than add this line somewhere in the web.config

    <log4net configSource="log.config"/>
    

    and then the file "log.config" has all the listeners configured. but don't forget to copy the file to your production/test environment. otherwise you may get strange error messages.

    hth