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.

Andre Cassar | 30 Oct 22:01 2014
Picon

Programmatically add newline to header & footer

Hi guys,

I'm configuring log4net programmatically and not using the xml configuration. I want to be able to add a newline to the header and footer. How can you do that? I tried %newline, \r,\n, &#13;&#10; but all in vain. 

My code looks like this:

PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "%date [%thread] %-5level %logger : %message%newline";
            patternLayout.Header = "%newline****** [Logging Started] ******%n[Date] [Thread ID] [Level] [Logger] : [Log Entry]&#13;&#10;";
            patternLayout.Footer = "****** [Logging Stoped] ******&#13;&#10;";
            
Any ideas please?


Thanks beforehand
Andre Cassar
Goyal, Nitin UTAS | 30 Oct 08:01 2014

How to push the List<> values in Ilogger.Info

Hi

 

I have a huge list of data say like 5k values and I want to push them into the logger.Info of log4net.

If there are individual string values, I am able to do so and accordingly modified the conversion pattern but now I want to push all those values in the list and thus is there anyway I can do so.

Also, I need to modify the conversion pattern too. For conversion pattern, I can make a string using for loop and override the Patternlayout class and set the conversion pattern for all the 5k values but how to put those values from List to those values?

 

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.

 

Calin Pavel | 17 Oct 11:55 2014
Picon

All threads blocked while logging

Hello everybody,

I do have an .NET application (Windows Service) that collects data from a lot of sources (DBs, log files, machines event logs, ...) and uses Log4Net to log details of the actions / execution.  As expected, I'm using a high number of threads to collect data, threads that are writing logs in some files (RollingFileAppenderer).

Lately it happens that the entire application is BLOCKED because all threads were trying to acquire a read lock, like in the stack trace:
000000001ac3d998 00000000774715fa [HelperMethodFrame: 000000001ac3d998] System.Threading.Thread.SleepInternal(Int32)
000000001ac3da90 000007fef747b5e9 System.Threading.Thread.Sleep(Int32)
000000001ac3dac0 000007fef5fb9631 System.Threading.ReaderWriterLockSlim.EnterMyLockSpin()
000000001ac3db90 000007fef5cd297e System.Threading.ReaderWriterLockSlim.TryEnterReadLockCore(TimeoutTracker)
000000001ac3dbf0 000007fef5cd28fa System.Threading.ReaderWriterLockSlim.TryEnterReadLock(TimeoutTracker)
000000001ac3dc40 000007fe98fb4efd log4net.Repository.Hierarchy.Logger.CallAppenders(log4net.Core.LoggingEvent)
000000001ac3dcc0 000007fe98fb4907 log4net.Repository.Hierarchy.Logger.Log(System.Type, log4net.Core.Level, System.Object, System.Exception)
000000001ac3dd30 000007fe98fb47f9 log4net.Core.LogImpl.Info(System.Object) 
....

Did you encountered this before or did anybody else reported similar problems?

May be it's important to mention:
- I'm using Log4Net 1.2.13, .NET 4.5 on Windows 2008 R2
- that my threads have a timeout, and if they do not finish the job in the given interval they are aborted.

In relation with this, I found a possible explanation of application hanging here: http://chabster.blogspot.ro/2013/07/a-story-of-orphaned-readerwriterlockslim.html

Could it be that the acquire of read lock in Logger.CallAppenderers method to generate our problems?

Thank you in advance,
Calin Pavel
Rob Richardson | 3 Oct 22:45 2014

Two logs have the same appenders

I want to get two independent sets of appender objects from the same configuration file, so that I can use
different file names in a FileAppender, for example.  But the standard way of getting appender objects is
to use the LogManager object, which is static.  Since there's only one LogManager, it will always return
the same set of appender objects.  So, I get one ILog object, get its FileAppender object, set its file name,
and write a message, and it appears in the expected file.  Then, I get another ILog object, get the
FileAppender object,  set its file name to some other file, and write a message, and that message appears in
the second file.  Finally, I go back to the first file appender, write another message, and it appears in the
second appenders file.  

Is there a way to copy a FileAppender object, or to get a new object for the same appender name out of the LogManager?

Thanks very much!

RobR, who will probably have to just build the logger programmatically instead of using a configuration file

Gmane