You are viewing a plain text version of this content. The canonical link for it is here.
Posted to log4net-user@logging.apache.org by Diana Santos <di...@liz-online.pt> on 2007/08/27 15:54:05 UTC

doubt about log4net configuration

 

Hi,

 

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

 

 


RE: doubt about log4net configuration

Posted by "Price, Randall" <ra...@vt.edu>.
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)

    {

        try

        {

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

            Exception ex = Server.GetLastError().GetBaseException();

 

            string strErrorMessage = "MESSAGE: "       + ex.Message

                                   + "\nSOURCE: "      + ex.Source

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

                                   + "\nQUERYSTRING: " +
Request.QueryString.ToString()

                                   + "\nTARGETSITE: "  + ex.TargetSite

                                   + "\nSTACKTRACE: "  + ex.StackTrace;

 

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

 
EventLog.WriteEntry(ConfigurationManager.AppSettings["ApplicationName"],
strErrorMessage, EventLogEntryType.Error);

 

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

            Session["Exception"] = ex;

            Session["Procedure"] = "Global.asax::Application_Error()";

            

            // Log to file.

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

            log.Error(strErrorMessage);

        }

        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.

 

Thanks,

 

Randall Price

Secure Enterprise Technology Initiatives

Microsoft Implementation Group

Virginia Tech Information Technology

1700 Pratt Drive

Blacksburg, VA  24060

Email:      Randall.Price@vt.edu

Phone:     (540) 231-4396

________________________________

From: Dave McEwan [mailto:dmcewan@harmonyis.com] 
Sent: Tuesday, August 28, 2007 9:21 AM
To: Log4NET User
Cc: raszka@hasam.cz; diana.santos@liz-online.pt
Subject: RE: doubt about log4net configuration

 

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.GetCurrentMeth
od().DeclaringType);

 

 

Thanks

Dave

 

________________________________

From: Price, Randall [mailto:randallp@vt.edu] 
Sent: Tuesday, August 28, 2007 7:55 AM
To: Log4NET User
Cc: raszka@hasam.cz; diana.santos@liz-online.pt
Subject: RE: doubt about log4net configuration

 

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:

 

Global.aspx:

 

    // Code that runs on application startup.

    void Application_Start(object sender, EventArgs e)

    {

        // Configure the Log4Net logging application.

        log4net.Config.XmlConfigurator.Configure();

        log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMeth
od().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 configuration):

 

Web.config:

 

<?xml version="1.0"?>

<configuration>

  <configSections>

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

      <sectionGroup name="scripting"
type="System.Web.Configuration.ScriptingSectionGroup,
System.Web.Extensions, 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,
PublicKeyToken=31bf3856ad364e35">

          <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" />

        </sectionGroup>

      </sectionGroup>

    </sectionGroup>

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

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

  </configSections>

 

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

  <log4net>

    <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 %newline"/>

      </layout>

    </appender>

    <root>

      <level value="ALL"/>

      <appender-ref ref="RollingFileAppender"/>

    </root>

  </log4net>

  ...

  ...

  ...

</configuration>

 

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):

 

..\logs\MyApp.log

..\logs\MyApp.log.2007-02-26

..\logs\MyApp.log.2007-02-25

..\logs\MyApp.log.2007-02-24

..etc..

 

 

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().Dec
laringType);

 

        protected void Page_Load(object sender, EventArgs e)

        {

            if (log.IsInfoEnabled)
log.Info(System.Reflection.MethodBase.GetCurrentMethod().Name + "()
started.");

 

            // Setup the common page headers.

            Headers.SetHeaders(Context);

 

            // Load some string contants.

            lblMainHeading.Text = Constants.DEFAULT_MAIN_HEADING_TEXT;

 

            try

            {

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

                string strErrorMessage = _GetErrorAsString();

                log.Error(strErrorMessage);

 

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

                _SendEmail(strErrorMessage);

 

                // Clear the Session variables associated with error
handling.

                Session.Remove("Exception");

                Session.Remove("ErrorProcedure");

                Session.Remove("ErrorMoreInfo");

                Session.Remove("ErrorStackTrace");

            }

            catch { }

 

            if (log.IsInfoEnabled)
log.Info(System.Reflection.MethodBase.GetCurrentMethod().Name + "()
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 configuration.

 

Hope this helps.

 

Randall Price

Secure Enterprise Technology Initiatives

Microsoft Implementation Group

Virginia Tech Information Technology

1700 Pratt Drive

Blacksburg, VA  24060

Email:      Randall.Price@vt.edu

Phone:     (540) 231-4396

________________________________

From: Radovan Raszka [mailto:raszka@hasam.cz] 
Sent: Tuesday, August 28, 2007 1:50 AM
To: Log4NET User
Subject: RE: doubt about log4net configuration

 

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));

or

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

Now you can send log messages to the log system:

 

log.Info(.....);

log.Warn(....);

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 Global.asax)

 

Radovan

	
________________________________


	From: Diana Santos [mailto:diana.santos@liz-online.pt] 
	Sent: Monday, August 27, 2007 3:54 PM
	To: log4net-user@logging.apache.org
	Subject: doubt about log4net configuration

	 

	Hi,

	 

	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

	 

	 


RE: doubt about log4net configuration

Posted by Dave McEwan <dm...@harmonyis.com>.
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.GetCurrentMeth
od().DeclaringType);

 

 

Thanks

Dave

 

  _____  

From: Price, Randall [mailto:randallp@vt.edu] 
Sent: Tuesday, August 28, 2007 7:55 AM
To: Log4NET User
Cc: raszka@hasam.cz; diana.santos@liz-online.pt
Subject: RE: doubt about log4net configuration

 

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:

 

Global.aspx:

 

    // Code that runs on application startup.

    void Application_Start(object sender, EventArgs e)

    {

        // Configure the Log4Net logging application.

        log4net.Config.XmlConfigurator.Configure();

        log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMeth
od().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 configuration):

 

Web.config:

 

<?xml version="1.0"?>

<configuration>

  <configSections>

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

      <sectionGroup name="scripting"
type="System.Web.Configuration.ScriptingSectionGroup,
System.Web.Extensions, 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,
PublicKeyToken=31bf3856ad364e35">

          <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" />

        </sectionGroup>

      </sectionGroup>

    </sectionGroup>

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

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

  </configSections>

 

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

  <log4net>

    <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 %newline"/>

      </layout>

    </appender>

    <root>

      <level value="ALL"/>

      <appender-ref ref="RollingFileAppender"/>

    </root>

  </log4net>

  ...

  ...

  ...

</configuration>

 

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):

 

..\logs\MyApp.log

..\logs\MyApp.log.2007-02-26

..\logs\MyApp.log.2007-02-25

..\logs\MyApp.log.2007-02-24

..etc..

 

 

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().Dec
laringType);

 

        protected void Page_Load(object sender, EventArgs e)

        {

            if (log.IsInfoEnabled)
log.Info(System.Reflection.MethodBase.GetCurrentMethod().Name + "()
started.");

 

            // Setup the common page headers.

            Headers.SetHeaders(Context);

 

            // Load some string contants.

            lblMainHeading.Text = Constants.DEFAULT_MAIN_HEADING_TEXT;

 

            try

            {

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

                string strErrorMessage = _GetErrorAsString();

                log.Error(strErrorMessage);

 

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

                _SendEmail(strErrorMessage);

 

                // Clear the Session variables associated with error
handling.

                Session.Remove("Exception");

                Session.Remove("ErrorProcedure");

                Session.Remove("ErrorMoreInfo");

                Session.Remove("ErrorStackTrace");

            }

            catch { }

 

            if (log.IsInfoEnabled)
log.Info(System.Reflection.MethodBase.GetCurrentMethod().Name + "()
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 configuration.

 

Hope this helps.

 

Randall Price

Secure Enterprise Technology Initiatives

Microsoft Implementation Group

Virginia Tech Information Technology

1700 Pratt Drive

Blacksburg, VA  24060

Email:      Randall.Price@vt.edu

Phone:     (540) 231-4396

  _____  

From: Radovan Raszka [mailto:raszka@hasam.cz] 
Sent: Tuesday, August 28, 2007 1:50 AM
To: Log4NET User
Subject: RE: doubt about log4net configuration

 

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));

or

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

Now you can send log messages to the log system:

 

log.Info(.....);

log.Warn(....);

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 Global.asax)

 

Radovan

	
  _____  


	From: Diana Santos [mailto:diana.santos@liz-online.pt] 
	Sent: Monday, August 27, 2007 3:54 PM
	To: log4net-user@logging.apache.org
	Subject: doubt about log4net configuration

	 

	Hi,

	 

	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

	 

	 


RE: doubt about log4net configuration

Posted by "Price, Randall" <ra...@vt.edu>.
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:

 

Global.aspx:

 

    // Code that runs on application startup.

    void Application_Start(object sender, EventArgs e)

    {

        // Configure the Log4Net logging application.

        log4net.Config.XmlConfigurator.Configure();

        log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMeth
od().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 configuration):

 

Web.config:

 

<?xml version="1.0"?>

<configuration>

  <configSections>

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

      <sectionGroup name="scripting"
type="System.Web.Configuration.ScriptingSectionGroup,
System.Web.Extensions, 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,
PublicKeyToken=31bf3856ad364e35">

          <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" />

        </sectionGroup>

      </sectionGroup>

    </sectionGroup>

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

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

  </configSections>

 

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

  <log4net>

    <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 %newline"/>

      </layout>

    </appender>

    <root>

      <level value="ALL"/>

      <appender-ref ref="RollingFileAppender"/>

    </root>

  </log4net>

  ...

  ...

  ...

</configuration>

 

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):

 

..\logs\MyApp.log

..\logs\MyApp.log.2007-02-26

..\logs\MyApp.log.2007-02-25

..\logs\MyApp.log.2007-02-24

..etc..

 

 

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().Dec
laringType);

 

        protected void Page_Load(object sender, EventArgs e)

        {

            if (log.IsInfoEnabled)
log.Info(System.Reflection.MethodBase.GetCurrentMethod().Name + "()
started.");

 

            // Setup the common page headers.

            Headers.SetHeaders(Context);

 

            // Load some string contants.

            lblMainHeading.Text = Constants.DEFAULT_MAIN_HEADING_TEXT;

 

            try

            {

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

                string strErrorMessage = _GetErrorAsString();

                log.Error(strErrorMessage);

 

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

                _SendEmail(strErrorMessage);

 

                // Clear the Session variables associated with error
handling.

                Session.Remove("Exception");

                Session.Remove("ErrorProcedure");

                Session.Remove("ErrorMoreInfo");

                Session.Remove("ErrorStackTrace");

            }

            catch { }

 

            if (log.IsInfoEnabled)
log.Info(System.Reflection.MethodBase.GetCurrentMethod().Name + "()
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 configuration.

 

Hope this helps.

 

Randall Price

Secure Enterprise Technology Initiatives

Microsoft Implementation Group

Virginia Tech Information Technology

1700 Pratt Drive

Blacksburg, VA  24060

Email:      Randall.Price@vt.edu

Phone:     (540) 231-4396

________________________________

From: Radovan Raszka [mailto:raszka@hasam.cz] 
Sent: Tuesday, August 28, 2007 1:50 AM
To: Log4NET User
Subject: RE: doubt about log4net configuration

 

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));

or

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

Now you can send log messages to the log system:

 

log.Info(.....);

log.Warn(....);

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 Global.asax)

 

Radovan

	
________________________________


	From: Diana Santos [mailto:diana.santos@liz-online.pt] 
	Sent: Monday, August 27, 2007 3:54 PM
	To: log4net-user@logging.apache.org
	Subject: doubt about log4net configuration

	 

	Hi,

	 

	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

	 

	 


RE: doubt about log4net configuration

Posted by Radovan Raszka <ra...@hasam.cz>.
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));
or
Ilog log = LogManager.GetLogger("yourLoggerName");
Now you can send log messages to the log system:
 
log.Info(.....);
log.Warn(....);
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 Global.asax)
 
Radovan


________________________________

	From: Diana Santos [mailto:diana.santos@liz-online.pt] 
	Sent: Monday, August 27, 2007 3:54 PM
	To: log4net-user@logging.apache.org
	Subject: doubt about log4net configuration
	
	

	 

	Hi,

	 

	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