logging-log4net-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Ron Grabowski <rongrabow...@yahoo.com>
Subject Re: doubt about log4net configuration
Date Tue, 28 Aug 2007 21:09:07 GMT
I think what Dave was getting at is that most people declare a single ILog instance as a readonly
static so every method in the class can access it. Creating an ILog is relatively expensive.
If you did it that way you're code would simple be:

            // Log to file.



----- Original Message ----
From: "Price, Randall" <randallp@vt.edu>
To: Log4NET User <log4net-user@logging.apache.org>
Cc: dmcewan@harmonyis.com
Sent: Tuesday, August 28, 2007 10:21:24 AM
Subject: RE: doubt about log4net configuration









 _filtered {font-family:Tahoma;panose-1:2 11 6 4 3 5 4 4 2 4;}
/* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{margin:0in;margin-bottom:.0001pt;font-size:12.0pt;font-family:"Times New Roman";}
a:link, span.MsoHyperlink
a:visited, span.MsoHyperlinkFollowed
	{margin-right:0in;margin-left:0in;font-size:12.0pt;font-family:"Times New Roman";}
 _filtered {margin:70.85pt 85.05pt 70.85pt 85.05pt;}

Hello Dave,


I am doing this because in the case of an
unhandled error somewhere in the ASP.NET application I can trap it in the Application_Error()
routine in Global.aspx, as follows:


    // Code that runs when an unhandled error occurs.

    void Application_Error(object sender, EventArgs e)




            // Get reference to the source of the
exception chain.

            Exception ex =


            string strErrorMessage = "MESSAGE: "       + ex.Message

+ "\nSOURCE: "     
+ ex.Source

+ "\nFORM: "       
+ Request.Form.ToString()

+ Request.QueryString.ToString()

+ ex.TargetSite

+ ex.StackTrace;


            // Log the details of the exception and
page state to the Event Log.

strErrorMessage, EventLogEntryType.Error);


            // Add information to Session so it can
be seen in AppError.aspx.

= ex;

= "Global.asax::Application_Error()";


            // Log to file.

            log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);



        catch { }



I suppose I could have moved the line
creating an instance of the Logger into the Application_Error() routine but
instead I have it in the Application_Start() routine.  I have not tried moving
it there but it should work.


Hope this helps clear up the confusion.




Randall Price

Secure Enterprise Technology Initiatives

Microsoft Implementation Group

Virginia Tech Information Technology

1700 Pratt Drive

VA  24060

Email:      Randall.Price@vt.edu

Phone:     (540) 231-4396

From: Dave McEwan

Sent: Tuesday, August 28, 2007
9:21 AM

To: Log4NET

Cc: raszka@hasam.cz;

Subject: RE: doubt about log4net


Hello Randall,


Could you tell me why you are creating an
instance of the Logger in both the Global.asax file and your class AppError?  Is this an oversight
or am I
just missing something?


Seems to me that you would not want this in the Global.asax file:

log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);






From: Price, Randall

Sent: Tuesday, August 28, 2007
7:55 AM

To: Log4NET

Cc: raszka@hasam.cz;

Subject: RE: doubt about log4net


Hello Diana,


Log4Net works great in ASP.NET.  I
use it in all my applications, whether ASP.NET, C# / VB.NET WinForms, Console
apps, etc.  Here is an example of how I use it in ASP.NET:


I always do the initial configuration in
Global.aspx in the Application_Start() routine:




    // Code that runs on application startup.

    void Application_Start(object sender, EventArgs e)


// Configure the Log4Net logging


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



The configuration file can be in a
stand-alone config file or in the web.config file.  I prefer the
web.config file so all of the configuration for my application can be done in
one place.  The following snippet from a typical web.config shows how I
configure the Log4Net settings.  All that is required is to add a
<section> entry for Log4Net in the <configSections>, then define
the <log4net> section, as follows (ignore the <sectionGroup> stuff
for the ASP.NET AJAX settings; they are not necessary for the Log4Net




<?xml version="1.0"?>



    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup,
System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,

      <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup,
Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

        <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection,
System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>

        <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup,
System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,

          <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection,
System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere" />

          <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection,
System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"

          <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection,
System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"




    <!-— Define a section for the Log4Net logger. -->

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



  <!-- This Log4Net section defines items required for the Log4Net
logger. -->


    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">

      <file value="logs\Web_Reporting.log"/>

      <appendToFile value="true"/>

      <maximumFileSize value="100KB"/>

      <maxSizeRollBackups value="2"/>

      <layout type="log4net.Layout.PatternLayout">

        <conversionPattern value="%date [%thread] %-5level %logger - %message




      <level value="ALL"/>

      <appender-ref ref="RollingFileAppender"/>








In this example, I have configured a
rolling file appender that tops out at 100KB.  If it exceeds 100KB it
renames the file and starts a new one.  Each day a new file is started and
the previous days’ file is renamed as follows (read more about the
appenders in the Log4Net documentation):









Then in each class where I want to log
something from, I get an instance of the logger and call it.  In this
example, I have an AppError.aspx page that gets called when an error occurs in
my ASP.NET application.  Here, I am logging the start and end of the
Page_Load() event, as well as an error message build from a custom routine, _GetErrorAsString(),
defined later in the code.


using log4net;

using log4net.Config;


namespace VT.MyApp


    public partial class AppError : System.Web.UI.Page


private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);


protected void Page_Load(object sender, EventArgs e)


if (log.IsInfoEnabled)
+ "() started.");


// Setup the common page headers.



// Load some string contants.

lblMainHeading.Text = Constants.DEFAULT_MAIN_HEADING_TEXT;




// Get the error message from the
Session variable, format it, and log it.

              string strErrorMessage =



// Check to send the error message
via Email to the appropriate destination.



    // Clear
the Session variables associated with error handling.






catch { }


if (log.IsInfoEnabled)
+ "() ended.");


}   // Page_Load()





}   // class AppError


}   // namespace VT.MyApp



That is basically it for configuring and
using Log4Net in an ASP.NET application.


One thing that is vitally important is
that the account that is running the ASP.NET application (usually by default
the IUSR_{machinename} account on the IIS server) must have the proper
permissions to the folder containing the log files.  In my example above,
that would be the C:\InetPub\wwwroot\MyApp\logs\ folder.  I gave the
IUSR_{machinename} account Modify permissions on this folder.  You might
also get it to work with just Read/Write but I haven’t tried that.


Log4Net is a great logging tool and fairly
easy to use.  It is quite customizable as you can see if you monitor this
forum because there are a lot of people out there writing customizations for
it.  I find it totally useful right out of the box with a little


Hope this helps.


Randall Price

 Enterprise Technology Initiatives

Microsoft Implementation Group

Virginia Tech Information Technology

1700 Pratt Drive

Blacksburg, VA   24060

Email:      Randall.Price@vt.edu

Phone:     (540)

From: Radovan Raszka

Sent: Tuesday, August 28, 2007
1:50 AM

To: Log4NET

Subject: RE: doubt about log4net


Hi Diana,

log4net is easy to use, I
try to explain in short.

Before you can write any
log entry, you must configure logging system. It is usually done during
constructing the main application's class (for example in Main() method for
console apps) and usually we use configuration file to do this:


using log4net;

using log4net.Config;

XmlConfigurator.Configure(new System.IO.FileInfo("log4net.config"));

this line configures log4net system using log4net.config file. This file
describes all targets, where log entries can be written to, short example is
attached (it allows to into console, file and Windows eventlog)

Now you can log anything you want - but some
coding is needed - you must get instance of logger (usually in constructor of
every class, inside which you want to log):

using log4net;

Ilog log = LogManager.GetLogger(typeof(yourClassName));


Ilog log = LogManager.GetLogger("yourLoggerName");

Now you can send log
messages to the log system:




log.Error(....); etc.


How message is written
into log target depends on configuration - see log4net documentation.

All I wrote is valid for
standard console or Windows application - I have no experience with logging in
ASP.NET, but there will not be big difference (l hope someone gives you
exact information, I think log4net should be probably configured in



Diana Santos [mailto:diana.santos@liz-online.pt] 

Sent: Monday, August 27, 2007 3:54


Subject: doubt about log4net




I need some ligths on log4net. A friend of mine told me that
we use the log4j and we only configure one file obtaining all log the for the
application without adding aditional code lines, including the log of the
actions taken in the data base. (INSERT / SELECT / DELETE …)

Konw, i‘m using the DotNetNuke framework to create a
portal, and i want to use the log4net to do some aditional logging. All the
articles and post that i read, some say that i have to add to all classes, that
i want to do the log, some lines as the import of the log4net and methots that
do the log… 

Is there any way to only configure a file like log4j?

thanks for the help.


P.S: i’m using ASP.NET 2.0



View raw message