Nicholas Dudas | 27 Mar 19:51 2015
Picon

Fwd: FileAppender ObjectDisposedException

I may have found a small bug in the file appender where the manual reset event is not cleaned up correctly during shutdown. 


--
Thanks,

Joseph L. Casale | 6 Mar 22:01 2015

Custom appender instantiation

I have a custom appender that uses parameters from the App.config file, however
I need to call an internal method after instantiation once the fields have been populated.

I see PreAppendCheck
Gert Kello | 5 Mar 13:01 2015
Picon

Debug info file for log4net release

Hi.

Is it possible to download the log4net.pdb file for log4net-1.2.13-bin-newkey.zip? So that debugging log4net would be possible without making custom build.


Is there some reason why it is not included in zip? Would You consider adding it to coming releases?

Gert

Gert Kello | 4 Mar 09:27 2015
Picon

AppenderSkeletion lock in DoAppend

Hi.

I'm trying to create a database appender which high throughput... I looked at code in AppenderSekeletion.DoAppend() method and saw following comment:

    public void DoAppend(LoggingEvent loggingEvent)
    {
      // This lock is absolutely critical for correct formatting
      // of the message in a multi-threaded environment.  Without
      // this, the message may be broken up into elements from
      // multiple thread contexts (like get the wrong thread ID).

      lock (this)
      {

I would like to remove this lock from my code but there's a couple of issues I do not understand:
1. As I do not know the internals of log4net well enough I do not understand why lock is important for message formatting? Is it because the Layout.Format is not supposed to be thread safe? Or is it because the same instance of m_renderWriter could be used by multiple threads (well, usage of m_renderWriter is protected by another lock, added later. But AFAIK the RenderLoggingEvent(LoggingEvent loggingEvent) is still not 100% thread safe)
2. The comment does not mention that lock is crucial for m_recursiveGuard to work correctly. That's my main complaint: I almost overlooked the issue of potentially skipped logging events.
3. What about implementations of IFilter.Decide? Are those (supposed to be) thread safe?

Gert
Thiemo.Kellner | 26 Feb 13:36 2015
Picon

64bit problem?

Hi all

 

I am at my wits’ end. We developped PowerShell script which uses log4net. I can run the script successfully from a batch file on my laptop but on the server I get

 

Attempting to perform the InitializeDefaultDrives operation on the 'FileSystem'

provider failed.

I:\WA_ANALYSE\AAA_INFA_CORE\Scripts\metadata_join_params-thiemo.ps1 :

Exception calling "LoadFile" with "1" argument(s): "The parameter is

incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))"

At line:1 char:1

+ I:\WA_ANALYSE\AAA_INFA_CORE\Scripts\metadata_join_params-thiemo.ps1

-stat_activi ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

~~~

    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorExcep

   tion

    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio

   n,metadata_join_params-thiemo.ps1

 

 

I found http://stackoverflow.com/questions/10249406/powershell-v2-load-a-com-interop-dll which points to a possible problem with mixing 32 dlls in 64 bit PowerShell. As my laptop is 32 and the server 64 bit, I was wondering if this might cause the problem. At least I could pin the line of code where the exception gets thrown: [void][Reflection.Assembly]::LoadFile($log4netDllPathString)

 

Has anyone an idea?

 

Liebe Grüsse/Cordialement/Cordialità

 

Thiemo Kellner

 

--

Office fédéral de la statistique
Espace de l'Europe 10
2010 Neuchâtel / Suisse

IT-AB

Tel     +41 32 71 36516

 

Christopher Landry | 12 Feb 21:00 2015

Dynamically change log levels confined to ThreadContext

I have a web app, and I’m trying to allow users to set the logging level via a query parameter. Got this working pretty easily.

 

The issue is that it doesn’t just change the logging level for that request, it’s changed for all requests that come in during the life cycle of that request – since I’m setting it back to the default level when the request is resolved.

 

I have tried adding the following in my appender, but it’s not working as I hoped.

 

<evaluator type=”log4net.spi.LevelEvaluator”>

     <threshold>

           <layout type=”log4net.Layout.RawPropertyLayout”>

                <key value=”LogLevel” />

     </threshold>

</evaluator>

 

And set a ThreadContext property called LogLevel to the appropriate level, but that doesn’t seem to work either.

 

Any thoughts? Have I missed something obvious?

 

Thanks!

emacslisp | 9 Feb 02:53 2015
Picon

how to make log4net exclude Stack Trace

By default, log4net will log Stack Trace.

I create a wraper which inherit from "ILog" and implement "ILog" interface
directly.

public class MyLogger : ILog
{
    ...
    Error(object message, Exception exception)
    {
        log.Error(exception.Message);//Now it will show message only.
    }
    ...
}

then log4net.ILog log = new
MyLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

it could work.

However, I want to config log4net without logging stack trace.

but I could not find any useful information.

--
View this message in context: http://apache-logging.6191.n7.nabble.com/how-to-make-log4net-exclude-Stack-Trace-tp53708.html
Sent from the Log4net - Users mailing list archive at Nabble.com.

Goyal, Nitin UTAS | 7 Jan 11:23 2015

Log4Net RollingFileAppender not adding Custom property in Win8/VS2013

Hi All

I am creating a custom property in Log4Net with Visual Studio 2010 on Win7 and it is able to create everything well with the correct property. But If i try to run the same program on Win8 and Visual Studio 2013, it do create the log file but without the custom property.

I have not edited anything and same thing is working in WIn7 but not in Win8.

I don't know what is changing in both of these environments. Can anyone give hint at what to look for?

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <configSections>

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

  </configSections>

  <log4net>

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

    <file type="log4net.Util.PatternString" value="C:\TSAS_DRU_Log\%property{LogName}" />

    <appendToFile value="true"/>

    <maxSizeRollBackups value="10"/>

    <maximumFileSize value="100MB"/>

    <staticLogFileName value="true"/>

    <layout type="TSAS_DRU_app.CsvPatternLayout, TSAS_DRU_app">

    </layout>

  </appender>

  <root>

    <level value="DEBUG" />

    <appender-ref ref="CsvFileAppender" />

  </root>

</log4net>

  </configuration>

 

I am setting the property in the code as following which is working correctly in WIn7 but not in Win8 where I have just updated the Visual studio as version 2013 with 2010:

string LogName = "TSAS_DRU_Log_" + date + ".csv";

    log4net.GlobalContext.Properties["LogName"] = LogName;

 

 

Nitin Goyal – Technical Lead, Software – Sensors & Integrated Systems

UTC AEROSPACE SYSTEMS

Netra Tech Park, Old Plot No.181, New Plot No. 40, EPIP Industrial Area, Part of Sy.No.28, Kundalahalli Village, Krishnaraja Puram Hobli, Bangalore 560 066, Karnataka, India

Tel: +91 80 673 80262  Mobile: +91 9886295724  Fax: +91 80 673 80005

nitin.goyal <at> utas.utc.com    www.utcaerospacesystems.com

 

CONFIDENTIALITY WARNING:  This message may contain proprietary and/or privileged information of UTC Aerospace Systems and its affiliated companies.  If you are not the intended recipient, please 1) do not disclose, copy, distribute or use this message or its contents, 2) advise the sender by return e-mail, and 3) delete all copies (including all attachments) from your computer.  Your cooperation is greatly appreciated.

 

Venkatasamy, Vanitha | 5 Dec 21:18 2014

log4Net Windows 2012

All,

  Our serves are upgraded to Windows 2012 R2, we have log4net implemented with alert emails. I have MultiThresholdNotifyingAppender ,which reads the event log from the event viewer, when it reaches the threshold limit ,it will send an  alert email to the developers.

 

Everything is working in old severs, but in Windows 2012 , the Timestamp is coming up wrong while reading from the event viewer .

 

It reads the first created log error (eg 2014-12-05T14:29:02.1578078-05:00 ) ,for all the errors logged after this , it’s reading the same time stamp. Pls see the attached code.

 

 

 

Thanks,

Vanitha Venkatasamy

XPAND Corporation.

 

 

 

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
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.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;


using System.Configuration;


namespace sendAlertAppender
{    
  
    public class MultiThresholdNotifyingAppender : AppenderSkeleton
    {
        public MultiThresholdNotifyingAppender()
        {
        }
    
        private Queue<LoggingEvent> loggingEventQueue ;  

        private DateTime windowStart ;
        protected int eventCount = 0; 
        Level _levelthreshold;
     
        TimeSpan _windowLength = TimeSpan.FromMinutes(Convert.ToDouble(System.Configuration.ConfigurationSettings.AppSettings["TimeLimit"].ToString()));
        int _hitThreshold = Convert.ToInt32(Convert.ToDouble(System.Configuration.ConfigurationSettings.AppSettings["Threshold"].ToString()));
      
        protected override void Append(LoggingEvent loggingEvent)
        {


            if (loggingEvent.MessageObject.ToString().Contains("404"))
                return;


            loggingEventQueue = new Queue<LoggingEvent>();
            

                    
            if (loggingEvent.Level < LevelThreshold)
            {
            
                if (loggingEventQueue.Count == 0)
                    return;
                if ((loggingEvent.TimeStamp - windowStart) >= WindowLength)
                {
                    //Error level is less than threshold and the time window has elapsed.  Remove any queued LoggingEvents    
                    //until all LoggingEvents in the queue fall within the time window.   
                    while (loggingEventQueue.Count > 0 && loggingEventQueue.Peek().TimeStamp - windowStart >= WindowLength)
                    {
                        loggingEventQueue.Dequeue();
                    }
                    windowStart = loggingEventQueue.Peek().TimeStamp;
                    return;
                }
            }
            //If we got here, then the Error level is >= the threshold.  We want to save the LoggingEvent and we MIGHT   
            //want to notify the administrator if the other criteria are met (number of errors within time window).
          
            

            loggingEventQueue.Enqueue(loggingEvent);
            

            //If this is the first error in the queue, start the time window. 
            //if (eventCount == 1)
            //    windowStart = loggingEvent.TimeStamp;


            string path = System.Configuration.ConfigurationSettings.AppSettings["filePath"].ToString();

            //String path = HttpContext.Current.Server.MapPath("filePath");
          
            int i;

            if (System.IO.File.Exists(path))
            {

                XDocument docs = XDocument.Load(path);

                XElement xele = docs.Descendants("ErrData").FirstOrDefault();
                if (xele != null)
                {
                    
                    i = Convert.ToInt32(docs.Descendants("ErrData").LastOrDefault().Element("Count").Value.ToString());
                    eventCount = i;
                    if (i < _hitThreshold + 1)
                    {
                        eventCount = eventCount + 1;
                        var temp = docs.Descendants("ErrData").FirstOrDefault().Element("Timestamp").Value.ToString();
                        windowStart = Convert.ToDateTime(temp);
                    }
                    else if (i > _hitThreshold)
                    {
                        eventCount = eventCount + 1;
                        var temp = docs.Descendants("ErrData").FirstOrDefault().Element("Timestamp").Value.ToString();
                        var temp2 = docs.Descendants("ErrData").LastOrDefault().Element("Timestamp").Value.ToString();
                        windowStart = Convert.ToDateTime(temp);


                    }
                }
                else
                {
                    eventCount = eventCount + 1;                    
                    windowStart = loggingEvent.TimeStamp;
                    
                }
            }
            else
            {
                eventCount = eventCount + 1;              
                windowStart = loggingEvent.TimeStamp;
            }


           //Now we're talking!  A lot of error messages in a short period of time.
            if ((loggingEvent.TimeStamp - windowStart >= WindowLength) && (eventCount < _hitThreshold))
            {
                //After sending the message, clear the LoggingEvents and reset the XMLFile.  
                eventCount = 1;
                ClearXMLFile(loggingEvent, path, eventCount);
                WritetoXML(path);
            }
            else if ((loggingEvent.TimeStamp - windowStart >= WindowLength)&& (eventCount > _hitThreshold))
            {
                //After sending the message, clear the LoggingEvents and reset the XMLFile.  If there are more error(>20)
logged in 5 min
                sendEmail(eventCount);
                eventCount = 0;
              
                ClearXMLFile(loggingEvent, path, eventCount);
            }
            else 
            {

                WritetoXML(path);


            }
      
            
        }

        private void WritetoXML(String path)
        {
            XDocument doc = null;
            XElement el;
            if (!System.IO.File.Exists(path))
            {

                doc = new XDocument(new XDeclaration("1.0", "utf-8", "no"));
                el = new XElement("root");
                XComment comment = new XComment("Log the error count and error message");
                doc.Add(comment);
            }
            else
            {
                doc = XDocument.Load(path);
            }
            XElement p1 = new XElement("ErrData");
            XElement p1Count = new XElement("Count", eventCount);
            XElement p1Timestamp = new XElement("Timestamp", windowStart);

            p1.Add(p1Count);
            p1.Add(p1Timestamp);

            if (doc.Root != null)
            {
                el = doc.Root;
                el.Add(p1);
            }
            else
            {
                el = new XElement("root");
                el.Add(p1);
            }


            try
            {
                doc.Add(el);

            }
            catch (Exception e)
            {

            }
            finally
            {
                doc.Save(path);
            }
        }

        private void ClearXMLFile(LoggingEvent loggingEvent, String path, int eventCount)
        {
            
            eventCount = 0;
            windowStart = loggingEvent.TimeStamp;
            XDocument docs = XDocument.Load(path);
            try
            {

                docs.Root.DescendantNodes().Remove();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                docs.Save(path);
            }
        }
        public void sendEmail(int count)
        {
            System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
            myMail.To = System.Configuration.ConfigurationSettings.AppSettings["EmailTo"].ToString();
            myMail.Cc = System.Configuration.ConfigurationSettings.AppSettings["EmailCc"].ToString();
            myMail.From = System.Configuration.ConfigurationSettings.AppSettings["EmailFrom"].ToString();
            string strSubject = System.Configuration.ConfigurationSettings.AppSettings["Source"].ToString();
            string strLog = System.Configuration.ConfigurationSettings.AppSettings["Log"].ToString();
            string strSmtp = System.Configuration.ConfigurationSettings.AppSettings["Smtp"].ToString();
            
            myMail.Subject = strSubject+" Error Alert";
            StringBuilder strMessgae = new StringBuilder();
            string serverName = System.Environment.MachineName.ToString().Substring(0,
Math.Min(System.Environment.MachineName.ToString().Length, 18));

            strMessgae.Append("\n" + "Alert Time:" + DateTime.Now + "\n\n");
            strMessgae.Append("EventLog Name: " + strLog + "\n\n");
            strMessgae.Append("Error log records exceeded the threshold, which indicates a major problem..." + "\n\n");
            strMessgae.Append(" Number of records logged in Server "+ serverName +" over the past 5 minutes are
("+count+") records" + "\n\n");



            myMail.Body = strMessgae.ToString();
            if (strSmtp == string.Empty)
            {
                SmtpMail.SmtpServer = "10.3.13.108";
            }
            else
            {
                SmtpMail.SmtpServer = strSmtp;
            }

            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);
            }
        }
        public string WriteString(String text)
        {
            string temp = string.Empty;
            temp = text.ToUpper();

            return temp;

        }
    }
    
}
Wim Sturkenboom | 21 Nov 12:29 2014

Multiple applications to a log4net remoting server

Hello all

 

Let me start saying that I know about nothing about log4net (even after trying to read documentation and trying to understand examples). So please forgive any incorrect wording. Based on examples, I’ve managed to let an application write to a remotingserver (sending to / listening on port 8085) and the remotingserver writes it nicely to a file.

 

I have modified the remotingserver example to a (windows) service and that also works fine.

 

Now I’m in need of this one remotingserver application to handle logs from different applications to different logfiles. The application side of things is not an issue, I think; just use another port.

 

But how do I write an application that contains multiple ‘remotingservers’ or one ‘remotingserver’ listening on different ports? Any pointers are at this stage appreciated. A thread for each port that I want to listen on? If so, how do I ‘tell the thread’ to use a specific configuration? Or something else.

 

Current code for remotingserver (in a windows service)

 

        protected override void OnStart(string[] args)

        {

            // TODO: Add code here to start your service.

 

            System.Diagnostics.EventLog.WriteEntry(String.Format("dsrp_log4net_service", version.getVersion()),

                                          ServiceName + "starting");

 

            // Log an info level message

            if (log.IsInfoEnabled) log.Info(String.Format("dsrp_log4net_service v{0} started", version.getVersion()));

 

            // Configure remoting. This loads the TCP channel as specified in the .config file.

            RemotingConfiguration.Configure(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, false);

 

            // Publish the remote logging server. This is done using the log4net plugin.

            log4net.LogManager.GetRepository().PluginMap.Add(new log4net.Plugin.RemoteLoggingServerPlugin("LoggingSink"));

 

            System.Diagnostics.EventLog.WriteEntry(String.Format("dsrp_log4net_service", version.getVersion()),

                                          ServiceName + "started");

       

        }

 

 

Thanks in advance for any help. WimS

xdzgor | 18 Nov 09:23 2014
Picon

BUT NOT

Hi - Is it possible to create "exceptions" in logger configurations? Like,
log all classes in a hierarchy except one sub-hierarchy?

For example, I have a lot of classes under a namespace (and sub-namespaces)
starting "Alpha". I'd like to DEBUG log all these classes, except any under
a particular sub-namespace ("Alpha.Import.Core").

Eg something like:

<appender name="one" ...>
  ...
</appender>

<logger name="Alpha" additivity="true" BUT NOT "Alpha.Import.Core">
  <level value="DEBUG" />
  <appender-ref ref="one" />
</logger>

Thanks for any tips,
Peter

--
View this message in context: http://apache-logging.6191.n7.nabble.com/BUT-NOT-tp53010.html
Sent from the Log4net - Users mailing list archive at Nabble.com.


Gmane