logging-log4net-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Brian Gustavsen" ...@adwiza.com>
Subject RE: Write to different Log Files
Date Thu, 30 Aug 2007 10:38:12 GMT
use the config file 
 
    <log4net>
      <appender name="RollingLogFileAppender1"
type="log4net.Appender.RollingFileAppender">
        <param name="File" value="app.log" />
        <param name="AppendToFile" value="true" />
        <param name="MaxSizeRollBackups" value="10" />
        <param name="MaximumFileSize" value="10MB" />
        <param name="RollingStyle" value="Size" />
        <param name="StaticLogFileName" value="true" />
        <layout type="log4net.Layout.PatternLayout">
          <param name="ConversionPattern" value="%d %-5p - %m %n" />
        </layout>
      </appender>
      <appender name="RollingLogFileAppender2"
type="log4net.Appender.RollingFileAppender">
        <param name="File" value="status.log" />
        <param name="AppendToFile" value="true" />
        <param name="MaxSizeRollBackups" value="10" />
        <param name="MaximumFileSize" value="10MB" />
        <param name="RollingStyle" value="Size" />
        <param name="StaticLogFileName" value="true" />
        <layout type="log4net.Layout.PatternLayout">
          <param name="ConversionPattern" value="%d %-5p - %m %n" />
        </layout>
      </appender>
 
      <root>
        <level value="ALL" />
        <appender-ref ref="RollingLogFileAppender2" />
      </root>
 
      <logger name="Datasync.net JobLog">
        <appender-ref ref="RollingLogFileAppender1" />
      </logger>
      
      <logger name="Datasync.net StatusLog">
        <appender-ref ref="RollingLogFileAppender2" />
      </logger>
    </log4net>
 
 
--
 
private static readonly ILog statusLog =
LogManager.GetLogger("Datasync.net StatusLog");

private static readonly ILog jobLog = LogManager.GetLogger("Datasync.net
JobLog");


________________________________

From: Maybhate, Dipty [mailto:Dipty.Maybhate@amd.com] 
Sent: 30. august 2007 00:26
To: Log4NET User
Subject: Write to different Log Files



Hi All

I am trying to develop a wrapper logging class in my project. We have
multiple class libraries, WCF services, Windows service, Consoles etc in
our project and want them to use this wrapper.

I am currently using FileAppenders and my wrapper configures log4net
programmatically (threshold level, log file name). 

I want every assembly which wants to use this class to log to a
different file and only that file. 

Could anyone please suggest me a way to do that? 

Thanks a lot in advance

Dipty

________________________________

From: Price, Randall [mailto:randallp@vt.edu] 
Sent: Wednesday, August 29, 2007 8:35 AM
To: Log4NET User
Cc: rongrabowski@yahoo.com; dmcewan@harmonyis.com; raszka@hasam.cz
Subject: RE: doubt about log4net configuration

 

Ron,

 

I see what you are saying about this.  I always generate a static ILog
instance in each class for use by all methods within that class.
However, it looks as it I did NOT do that for the Global.aspx file.  No
reason that I can of why I did it this way, but it should work by moving
the code to create a single ILog instance for the entire class.

 

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: Ron Grabowski [mailto:rongrabowski@yahoo.com] 
Sent: Tuesday, August 28, 2007 5:09 PM
To: Log4NET User
Subject: Re: doubt about log4net configuration

 

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.

            log.Error(strErrorMessage);

 

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

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

	 

	 

 


Mime
View raw message