Herrmann, David G | 2 Nov 2011 22:03
Picon
Favicon

log4net advice

To: Someone more knowledgeable in log4net than myself.

 

I have just downloaded the 1.2.11 version of log4net. I am learning how to use it and can get basic logging done in my application. However, I have a need for something that I’m not sure how to do if it is possible at all.

 

I need to be able to log to different log files within the same application where I don’t know the log file names in advance so I cannot create the necessary appenders in my app.config file before hand. I will only know the log file name at run time. Is there a way I can do this? Can I use one appender that is defined in my app.config file but substitute a different file name at run time somehow? Or is there a way to set up my logger using just the log4net API?

 

I see that log4net comes with an extensive API but if this is possible I don’t see it in the API. If I can specify log file names at run time, how would I do that?

 

Thank you very much for any advice on this.

 

-Dave Herrmann

 

Richard Pennenga | 2 Nov 2011 23:07

RE: log4net advice

David,

 

You could loop through all the Appenders, looking for the one with your specific name, and then change the appropriate property at runtime.

 

I found really useful code for looping through & finding Appenders from Andrew Andrew Elmhorst and Nicko Cadell, posted here:  http://www.l4ndash.com/Log4NetMailArchive%2Ftabid%2F70%2Fforumid%2F1%2Fpostid%2F15439%2Fview%2Ftopic%2FDefault.aspx

 

I had to tweak it a bit more for BufferingForwarding Appenders – but if your Appenders are hung off the root and are just rollingfile Appenders or something else with no indirection, you can probably use the simplest sample code.

 

If you need more help feel free to repost.

 

Richard J. Pennenga

Software Developer

 

Angel Medical Systems, Inc.

T:  732-542-5551 x110

F:  732-542-5560

rpennenga <at> angel-med.com

www.angel-med.com            

 

Herrmann, David G | 3 Nov 2011 00:40
Picon
Favicon

RE: log4net advice - Changing log file name at run time

I checked that reference on how to loop through all the Appenders looking for the one I wanted and then changing the File property to a different file name. However, will this affect other threads that use the same appender? I have a web service that can process requests on multiple threads. Each method in my web service will use the same appender, but I want a different file name for each thread. I don’t know in advance what all the file names will be, I only know that at run time.  If one thread loops through all the appenders as this link shows and changes the File property and then another thread comes in and changes the File property on the same appender, will that affect the first thread? In other words, will I see my log messages for one thread being split up across multiple log files?

 

Another option I’ve seen is the following.

Create the following appender and logger entries in the config file:

 

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

      <file type="log4net.Util.PatternString" value="Logs/%property{LogFileName}.log" />

      <appendToFile value="true" />

      <rollingStyle value="Size" />

      <maxSizeRollBackups value="10" />

      <maximumFileSize value="100MB" />

      <staticLogFileName value="true" />

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

        <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss} %-5level : [%logger] - %message%newline" />

      </layout>

</appender>

<logger name="SPM.SERVER">     

      <level value="DEBUG" />

      <appender-ref ref="RollingPatternFileAppender" />            

</logger>

 

Then when a thread gets a logger it does the following:

 

ILog logger = LogManager.GetLogger("SPM.SERVER");

       log4net.ThreadContext.Properties["LogFileName"] = connectionInfo.serverName;

       XmlConfigurator.Configure();

 

Where connectionInfo.serverName contains the new name that I want to use as the log file name. It seems this would be more thread safe since I am only changing the properties in my thread context. But I am not sure of that.

 

Is one of these methods more thread safe than the other? Are they both thread safe?

 

Thank you for any insights into this.

-Dave Herrmann

 

From: Richard Pennenga [mailto:rpennenga <at> angel-med.com]
Sent: Wednesday, November 02, 2011 3:08 PM
To: Log4NET User
Subject: RE: log4net advice

 

David,

 

You could loop through all the Appenders, looking for the one with your specific name, and then change the appropriate property at runtime.

 

I found really useful code for looping through & finding Appenders from Andrew Andrew Elmhorst and Nicko Cadell, posted here:  http://www.l4ndash.com/Log4NetMailArchive%2Ftabid%2F70%2Fforumid%2F1%2Fpostid%2F15439%2Fview%2Ftopic%2FDefault.aspx

 

I had to tweak it a bit more for BufferingForwarding Appenders – but if your Appenders are hung off the root and are just rollingfile Appenders or something else with no indirection, you can probably use the simplest sample code.

 

If you need more help feel free to repost.

 

Richard J. Pennenga

Software Developer

 

Angel Medical Systems, Inc.

T:  732-542-5551 x110

F:  732-542-5560

rpennenga <at> angel-med.com

www.angel-med.com            

 

Radovan Raszka | 3 Nov 2011 11:19
Picon
Favicon

RE: log4net advice - Changing log file name at run time

You can add/remove appender dynamically at runtime. Perhaps you can create separate appender for each thread (and destroy it when thread finishes).
Here's my code I'm using for enabling/disabling Fileappender at runtime:
 

private

static void enableDebugLog(bool enable)

{

RollingFileAppender rfa = null;

log4net.Repository.Hierarchy.Logger root = ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root;

foreach (AppenderSkeleton appender in LogManager.GetRepository().GetAppenders())

{

rfa = appender as RollingFileAppender;

if (rfa != null) //found file appender

break;

}

if (enable)

{

if (rfa != null) return; // appender already enabled!

RollingFileAppender debugLog = new RollingFileAppender();

debugLog.AppendToFile = true;

debugLog.File = Folder_Log + "Service";

debugLog.Layout = new log4net.Layout.PatternLayout("%date{dd-MM-yyyy HH:mm:ss,fff} %5level [%2thread] %message (%logger{1}:%line)%n");

debugLog.RollingStyle = RollingFileAppender.RollingMode.Date;

debugLog.Threshold = log4net.Core.Level.Debug;

debugLog.StaticLogFileName = false;

debugLog.DatePattern = ".yyyy-MM-dd.lo\\g";

debugLog.ActivateOptions();

root.AddAppender(debugLog);

}

else

{

if (rfa == null) return; // appenderalready disabled !

root.RemoveAppender(rfa);

rfa.Close();

}

}

Maybe it helps a little...
RR
Od: Herrmann, David G [mailto:david.g.herrmann <at> intel.com]
Odesláno: 3. listopadu 2011 0:41
Komu: Log4NET User
Předmět: RE: log4net advice - Changing log file name at run time

I checked that reference on how to loop through all the Appenders looking for the one I wanted and then changing the File property to a different file name. However, will this affect other threads that use the same appender? I have a web service that can process requests on multiple threads. Each method in my web service will use the same appender, but I want a different file name for each thread. I don’t know in advance what all the file names will be, I only know that at run time.  If one thread loops through all the appenders as this link shows and changes the File property and then another thread comes in and changes the File property on the same appender, will that affect the first thread? In other words, will I see my log messages for one thread being split up across multiple log files?

 

Another option I’ve seen is the following.

Create the following appender and logger entries in the config file:

 

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

      <file type="log4net.Util.PatternString" value="Logs/%property{LogFileName}.log" />

      <appendToFile value="true" />

      <rollingStyle value="Size" />

      <maxSizeRollBackups value="10" />

      <maximumFileSize value="100MB" />

      <staticLogFileName value="true" />

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

        <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss} %-5level : [%logger] - %message%newline" />

      </layout>

</appender>

<logger name="SPM.SERVER">     

      <level value="DEBUG" />

      <appender-ref ref="RollingPatternFileAppender" />            

</logger>

 

Then when a thread gets a logger it does the following:

 

ILog logger = LogManager.GetLogger("SPM.SERVER");

       log4net.ThreadContext.Properties["LogFileName"] = connectionInfo.serverName;

       XmlConfigurator.Configure();

 

Where connectionInfo.serverName contains the new name that I want to use as the log file name. It seems this would be more thread safe since I am only changing the properties in my thread context. But I am not sure of that.

 

Is one of these methods more thread safe than the other? Are they both thread safe?

 

Thank you for any insights into this.

-Dave Herrmann

 

From: Richard Pennenga [mailto:rpennenga <at> angel-med.com]
Sent: Wednesday, November 02, 2011 3:08 PM
To: Log4NET User
Subject: RE: log4net advice

 

David,

 

You could loop through all the Appenders, looking for the one with your specific name, and then change the appropriate property at runtime.

 

I found really useful code for looping through & finding Appenders from Andrew Andrew Elmhorst and Nicko Cadell, posted here:  http://www.l4ndash.com/Log4NetMailArchive%2Ftabid%2F70%2Fforumid%2F1%2Fpostid%2F15439%2Fview%2Ftopic%2FDefault.aspx

 

I had to tweak it a bit more for BufferingForwarding Appenders – but if your Appenders are hung off the root and are just rollingfile Appenders or something else with no indirection, you can probably use the simplest sample code.

 

If you need more help feel free to repost.

 

Richard J. Pennenga

Software Developer

 

Angel Medical Systems, Inc.

T:  732-542-5551 x110

F:  732-542-5560

rpennenga <at> angel-med.com

www.angel-med.com            

 

Richard Pennenga | 3 Nov 2011 14:44

RE: log4net advice - Changing log file name at run time

If you create a new logger for each thread (saving the ILog reference in thread-local storage), you can define whatever appender you want for it.  I would think that would eliminate thread safety issues.

 

Richard J. Pennenga

Software Developer

 

Angel Medical Systems, Inc.

T:  732-542-5551 x110

F:  732-542-5560

rpennenga <at> angel-med.com

www.angel-med.com            

 

 

costan | 8 Nov 2011 08:55
Picon
Favicon

Log4Net and MySQL with C# .NET Framework 4.0


Hello everyome Im trying to post some errors to my MySQL-Database, but it
happens nothing. Im trying it since 5 Days now and cant find a solution. 
At the first I downloaded the MySQL-Connector and added the MySQL.Data.dll
to the reference of the Project. 

Then I created my own Configfile it looks like this one:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
  </configSections>
  <log4net>
    <root>
      <!-- OFF, FATAL, ERROR, WARN, DEBUG, INFO, ALL -->
      <level value="ALL"/>
      <appender-ref ref="FileAppender"/>
      <appender-ref ref="ADONetAppender"/>
    </root>
    <appender name="FileAppender"
type="log4net.Appender.RollingFileAppender" >

      
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">

      </layout>
    </appender>

    <appender name="ADONetAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1" />
      <connectionType value="MySql.Data.MySqlClient.MySqlConnection,
MySql.Data, Version=6.4.4.0, Culture=neutral,
PublicKeyToken=c5687fc88969c44d" />
      <connectionString value="Server=MyIP;
Database=themenportale_log4net;Uid=log4netuser;Pwd=12345" />
      <commandText value="INSERT INTO 'Log' (Message) VALUES (?message)" />
      <parameter>
        <parameterName value="?message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message" />
        </layout>
      </parameter>
    </appender>
  </log4net>
</configuration>

The Fileappender wirks very well, but the MySQL-Appender do nothing. I tryed
to do this Tutorial but It couldn't help me:
http://rafayal.blogspot.com/2009/05/using-log4net-with-c-and-mysql.html
It doesn't work too. 

I think my problem is the Configfile and I have somewhere a mistake. 
--

-- 
View this message in context: http://old.nabble.com/Log4Net-and-MySQL-with-C--.NET-Framework-4.0-tp32801621p32801621.html
Sent from the Log4net - Users mailing list archive at Nabble.com.

SEGERS Steven (CNH | 8 Nov 2011 13:52

RE: Log4Net and MySQL with C# .NET Framework 4.0

Hello Costan

I think it's best to enable internal debugging. That should give you more information.

http://logging.apache.org/log4net/release/faq.html#internalDebug

Best Regards

Steven
-----Original Message-----
From: costan [mailto:spickomm <at> yahoo.de] 
Sent: dinsdag 8 november 2011 8:55
To: log4net-user <at> logging.apache.org
Subject: Log4Net and MySQL with C# .NET Framework 4.0

Hello everyome Im trying to post some errors to my MySQL-Database, but it happens nothing. Im trying it
since 5 Days now and cant find a solution. 
At the first I downloaded the MySQL-Connector and added the MySQL.Data.dll to the reference of the
Project. 

Then I created my own Configfile it looks like this one:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
  </configSections>
  <log4net>
    <root>
      <!-- OFF, FATAL, ERROR, WARN, DEBUG, INFO, ALL -->
      <level value="ALL"/>
      <appender-ref ref="FileAppender"/>
      <appender-ref ref="ADONetAppender"/>
    </root>
    <appender name="FileAppender"
type="log4net.Appender.RollingFileAppender" >

      
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">

      </layout>
    </appender>

    <appender name="ADONetAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1" />
      <connectionType value="MySql.Data.MySqlClient.MySqlConnection,
MySql.Data, Version=6.4.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
      <connectionString value="Server=MyIP;
Database=themenportale_log4net;Uid=log4netuser;Pwd=12345" />
      <commandText value="INSERT INTO 'Log' (Message) VALUES (?message)" />
      <parameter>
        <parameterName value="?message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message" />
        </layout>
      </parameter>
    </appender>
  </log4net>
</configuration>

The Fileappender wirks very well, but the MySQL-Appender do nothing. I tryed to do this Tutorial but It
couldn't help me:
http://rafayal.blogspot.com/2009/05/using-log4net-with-c-and-mysql.html
It doesn't work too. 

I think my problem is the Configfile and I have somewhere a mistake. 
--
View this message in context: http://old.nabble.com/Log4Net-and-MySQL-with-C--.NET-Framework-4.0-tp32801621p32801621.html
Sent from the Log4net - Users mailing list archive at Nabble.com.

costan | 9 Nov 2011 08:29
Picon
Favicon

RE: Log4Net and MySQL with C# .NET Framework 4.0


Hi. Im trying to enable the internal.debugging like this: Do not work. But
the connection to the database I have already done and have found the
problem :). But this internaldebugger writes nothing to the file when I
cause the error :(

  <appSettings>
    <add key="log4net.Internal.Debug" value="true"/>
  </appSettings>
  <system.diagnostics>
    <trace autoflush="true">
      <listeners>
        <add
            name="textWriterTraceListener"
            type="System.Diagnostics.TextWriterTraceListener"
            initializeData="d:\bugLogs.txt" />
      </listeners>
    </trace>
  </system.diagnostics>

SEGERS Steven (CNH) wrote:
> 
> Hello Costan
> 
> I think it's best to enable internal debugging. That should give you more
> information.
> 
> http://logging.apache.org/log4net/release/faq.html#internalDebug
> 
> Best Regards
> 
> Steven
> -----Original Message-----
> From: costan [mailto:spickomm <at> yahoo.de] 
> Sent: dinsdag 8 november 2011 8:55
> To: log4net-user <at> logging.apache.org
> Subject: Log4Net and MySQL with C# .NET Framework 4.0
> 
> 
> Hello everyome Im trying to post some errors to my MySQL-Database, but it
> happens nothing. Im trying it since 5 Days now and cant find a solution. 
> At the first I downloaded the MySQL-Connector and added the MySQL.Data.dll
> to the reference of the Project. 
> 
> Then I created my own Configfile it looks like this one:
> 
> <?xml version="1.0"?>
> <configuration>
>   <configSections>
>     <section name="log4net"
> type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
>   </configSections>
>   <log4net>
>     <root>
>       <!-- OFF, FATAL, ERROR, WARN, DEBUG, INFO, ALL -->
>       <level value="ALL"/>
>       <appender-ref ref="FileAppender"/>
>       <appender-ref ref="ADONetAppender"/>
>     </root>
>     <appender name="FileAppender"
> type="log4net.Appender.RollingFileAppender" >
>       
>       
>       <rollingStyle value="Size" />
>       <maxSizeRollBackups value="10" />
>       <maximumFileSize value="10MB" />
>       <staticLogFileName value="true" />
>       <layout type="log4net.Layout.PatternLayout">
>         
>       </layout>
>     </appender>
> 
>     <appender name="ADONetAppender"
> type="log4net.Appender.AdoNetAppender">
>       <bufferSize value="1" />
>       <connectionType value="MySql.Data.MySqlClient.MySqlConnection,
> MySql.Data, Version=6.4.4.0, Culture=neutral,
> PublicKeyToken=c5687fc88969c44d" />
>       <connectionString value="Server=MyIP;
> Database=themenportale_log4net;Uid=log4netuser;Pwd=12345" />
>       <commandText value="INSERT INTO 'Log' (Message) VALUES (?message)"
> />
>       <parameter>
>         <parameterName value="?message" />
>         <dbType value="String" />
>         <size value="4000" />
>         <layout type="log4net.Layout.PatternLayout">
>           <conversionPattern value="%message" />
>         </layout>
>       </parameter>
>     </appender>
>   </log4net>
> </configuration>
> 
> The Fileappender wirks very well, but the MySQL-Appender do nothing. I
> tryed to do this Tutorial but It couldn't help me:
> http://rafayal.blogspot.com/2009/05/using-log4net-with-c-and-mysql.html
> It doesn't work too. 
> 
> I think my problem is the Configfile and I have somewhere a mistake. 
> --
> View this message in context:
> http://old.nabble.com/Log4Net-and-MySQL-with-C--.NET-Framework-4.0-tp32801621p32801621.html
> Sent from the Log4net - Users mailing list archive at Nabble.com.
> 
> 
> 

--

-- 
View this message in context: http://old.nabble.com/Log4Net-and-MySQL-with-C--.NET-Framework-4.0-tp32801621p32809097.html
Sent from the Log4net - Users mailing list archive at Nabble.com.

Venkatasamy, Vanitha | 11 Nov 2011 20:40
Favicon

RE: Email alert from log4net

Hi ,

 I tried it with BufferingForwardingAppender , it has the buffersize but no time limit. My requirement is sending mail if  20 errors are logged within  5 min.

 

 

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

    <bufferSize value="20" />

    <lossy value="true" />

    <evaluator type="log4net.Core.LevelEvaluator">

        <threshold value="Error"/>

    </evaluator>

    <appender-ref ref="EventLogAppender" />

</appender>

               

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

      <param name="LogName" value="PWebLogs" />

      <param name="ApplicationName" value="Test" />          

      <filter type="log4net.Filter.LevelRangeFilter">

        <acceptOnMatch value="true" />

        <levelMin value="INFO" />

        <levelMax value="FATAL" />

      </filter>

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

        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />

      </layout>

    </appender>

 

Thanks,

 

 

From: Ron Grabowski [mailto:rongrabowski <at> yahoo.com]
Sent: Thursday, October 27, 2011 8:04 PM
To: Log4NET User
Subject: Re: Email alert from log4net

 

You could extend BufferingForwardingAppender to wrap your original appender and add logic for sending mail when there's too much traffic after inspecting the buffer and to stop messages from forwarding until a certain timeout period has passed.

 

From: "Venkatasamy, Vanitha" <Vanitha.Venkatasamy <at> xpandcorp.com>
To: Log4NET User <log4net-user <at> logging.apache.org>
Sent: Thursday, October 27, 2011 11:37 AM
Subject: Email alert from log4net

Hi ,

 

I need some idea to implement the following requirement in the web application .

 

I am using log4net in a custom dll to log the errors. I completed the log4net implementation and its working fine.[aspx errors are logged in Event Log and the asp errors are logged in FileAppender] .All the  .loggerError() methods are in the custom dll.

 

Now I want to monitor the logging, suppose if there is a situation like the .loggerError() method is called more than 10 times in just 15 mins  because of Fatal error or if database is down, then I want to track that and send email to admin. Is anybody implemented similar requirement or is there any solution in Log4net.

 

 

 

 


This message contains Devin Group confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail.
Please notify the sender immediately by e-mail if you have received this e-mail in error and delete this e-mail from your system. E-mail transmissions cannot be guaranteed secure, error-free and information could be intercepted, corrupted, lost, destroyed, arrive late, incomplete, or contain viruses. The sender therefore does not accept liability for errors or omissions in the contents of this message which may arise as result of transmission. If verification is required please request hard-copy version.

 



This message contains Devin Group confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail.
Please notify the sender immediately by e-mail if you have received this e-mail in error and delete this e-mail from your system. E-mail transmissions cannot be guaranteed secure, error-free and information could be intercepted, corrupted, lost, destroyed, arrive late, incomplete, or contain viruses. The sender therefore does not accept liability for errors or omissions in the contents of this message which may arise as result of transmission. If verification is required please request hard-copy version.
Venkatasamy, Vanitha | 15 Nov 2011 16:53
Favicon

How to initialize Custom appender in log4net

 

Hi All,

   I am using custom appender to send an email if 20 errors are logged in Event Viewer within 5 minutes. I wrote the custom appender and placed the .cs file in the App_Code folder. The project is compiled and build successfully . But nothing is happening when the error is occurred in the application side. Please see the config settings and the custom appender. I think I am missing some config setting or assembly reference.

 

Config

 

      <configSections>

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

            <section name="MultiThresholdNotifyingAppender" type="Log4NetExtensions.MultiThresholdNotifyingAppender, MultiThresholdNotifyingAppender"/>

      </configSections>

       <log4net debug="true">

            <appender name="MultiThresholdNotifyingAppender" type="Log4NetExtensions.MultiThresholdNotifyingAppender,MultiThresholdNotifyingAppender">

                  <!--<evaluator type="log4net.Core.LevelEvaluator">

        <threshold value="Error"/>

      </evaluator>

      <Level value="Error"/>

      <TimeSpan  value="00:05:00"/>-->

                  <!--<evaluator type="log4net.Core.LevelEvaluator,log4net">-->

      <LevelThreshold  value="ERROR"/>

                  <!--</evaluator>-->

                  <appender-ref ref="EventLogAppender"/>

            </appender>

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

                  <param name="LogName" value="PortalWebLogs"/>

                  <param name="ApplicationName" value="Portals"/>

                  <filter type="log4net.Filter.LevelRangeFilter">

                        <acceptOnMatch value="true"/>

                        <levelMin value="INFO"/>

                        <levelMax value="FATAL"/>

                  </filter>

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

                        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>

                  </layout>

            </appender>

            <root>

                  <level value="ALL"/>

                  <priority value="ERROR"/>

                  <appender-ref ref="MultiThresholdNotifyingAppender"/>

                  <!--<appender-ref ref="EventLogAppender"/>-->

            </root>

      </log4net>

 

 

MultiThresholdNotifyingAppender.cs in App_code folder

 

using System;

using System.Collections.Generic;

using System.Web;

using log4net;

 

using log4net.Core;

using System.Threading;

using log4net.Appender;

using log4net.Config;

using System.Web.Mail;

using System.Windows.Forms;

 

 

/// <summary>

/// Summary description for Class1

/// </summary>

 

 

 

namespace Log4NetExtensions

{

    public class MultiThresholdNotifyingAppender : AppenderSkeleton

    {

        public MultiThresholdNotifyingAppender()

        {

        }

        private Queue<LoggingEvent> loggingEventQueue = new Queue<LoggingEvent>();

 

 

        private DateTime windowStart = DateTime.Now;

 

 

        Level _levelthreshold;

        TimeSpan _windowLength = TimeSpan.FromMinutes(1);//its 5 min but 1 min is to test

        int _hitThreshold = 1;//its 20 but 1 is to test the code

 

        protected override void Append(LoggingEvent loggingEvent)

        {

            sendEmail(); //.to test whether is function is being called..But no its not fired.

 

            if (loggingEvent.Level < LevelThreshold)

            {

 

                if (loggingEventQueue.Count == 0)

                    return;

                if ((loggingEvent.TimeStamp - windowStart) >= WindowLength)

                {

                    while (loggingEventQueue.Count > 0 && loggingEventQueue.Peek().TimeStamp - windowStart >= WindowLength)

                    {

                        loggingEventQueue.Dequeue();

                    }

                    windowStart = loggingEventQueue.Peek().TimeStamp;

                    return;

                }

            }

            loggingEventQueue.Enqueue(loggingEvent);

            //If this is the first error in the queue, start the time window.

            if (loggingEventQueue.Count == 1)

                windowStart = loggingEvent.TimeStamp;

            //Too few messages to qualify for notification.

            if (loggingEventQueue.Count < HitThreshold - 1)

                return;

            if (loggingEvent.TimeStamp - windowStart >= WindowLength)

            {

               

                sendEmail();

            }

            //After sending the message, clear the LoggingEvents and reset the time window. 

            loggingEventQueue.Clear();

            windowStart = loggingEvent.TimeStamp;

        }

        public void sendEmail()

        {

            System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();

            myMail.To = "cc <at> cc.com";

            myMail.From = "xx <at> xx.com";

            myMail.Subject = "Error";

            myMail.Body = "Hello World";

            SmtpMail.SmtpServer = "xx.x.xx.xx";

 

            SmtpMail.Send(myMail);

 

        }

        public Level LevelThreshold

        {

            get

            {

                return _levelthreshold;

            }

            set

            {

                _levelthreshold = value;

            }

        }

 

 

        public TimeSpan WindowLength

        {

            get

            {

                return _windowLength;

            }

            set

            {

                _windowLength = value;

            }

        }

 

 

 

        public int HitThreshold

        {

            get

            {

                return _hitThreshold;

            }

            set

            {

                _hitThreshold = value;

            }

        }

        public void Append(LoggingEvent[] loggingEvents)

        {

            foreach (LoggingEvent le in loggingEvents)

            {

                Append(le);

            }

        }

    }

 

}

   

 

Thanks,

Vanitha



This message contains Devin Group confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail.
Please notify the sender immediately by e-mail if you have received this e-mail in error and delete this e-mail from your system. E-mail transmissions cannot be guaranteed secure, error-free and information could be intercepted, corrupted, lost, destroyed, arrive late, incomplete, or contain viruses. The sender therefore does not accept liability for errors or omissions in the contents of this message which may arise as result of transmission. If verification is required please request hard-copy version.

Gmane