Saturday, May 25, 2013
 
The best way to analyze your logs! Minimize
 Log4Net Mail archive   

The Log4Net mailing list is a great source of information about using log4Net, in this forum we collect all the messages in the log4net user list and some selected threads from the developer list.

Subject: Disable/enable appender for all loggers
Prev Next
You are not authorized to post a reply.

Author Messages
Radovan Raszka

07/27/2007 8:23 AM  

Hello,
I am using three appenders in my log4net configuration (see bellow). But I need programatically disable and reenable RollingFile appender at certain situations. Is there any simple solution? I tried to use programatic configuration only.

My config:
<log4net>
                <appender name="Console" type="log4net.Appender.ConsoleAppender">
                        <layout type="log4net.Layout.PatternLayout">
                                <!-- Pattern to output the caller's file name and line number -->
                                <conversionPattern value="%date{HH:mm:ss,fff} %5level [%thread] %message%n" />
                        </layout>
                        <Threshold value="DEBUG" />
                </appender>

                <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
                        <appendToFile value="true" />
                        <file value="Service.log" />
                        <layout type="log4net.Layout.PatternLayout">
                                <conversionPattern value="%date{dd-MM-yyyy HH:mm:ss,fff} %5level [%2thread] %message (%logger{1}:%line)%n" />

                        </layout>
                        <rollingStyle value="Date" />
                        <Threshold value="DEBUG" />
                </appender>

                <appender name="EvLog" type="log4net.Appender.EventLogAppender">
                        <ApplicationName value="IPserver" />
                        <layout type="log4net.Layout.PatternLayout">
                                <conversionPattern value="[%thread] %message (%logger{1})" />
                        </layout>
                        <Threshold value="INFO" />
                </appender>

                <root>
                        <level value="DEBUG" />
                        <appender-ref ref="RollingFile" />
                        <appender-ref ref="Console" />
                        <appender-ref ref="EvLog" />
                </root>
        </log4net>

I tried to complete rewrite this config into C# code:

private readonly log4net.Appender.ConsoleAppender AppConsole;
private readonly log4net.Appender.RollingFileAppender AppFile;
private readonly log4net.Appender.EventLogAppender AppEvlog;
private log4net.Repository.Hierarchy.RootLogger rootLog;
//XmlConfigurator.Configure(new System.IO.FileInfo(IPserverCore.IPserver.GetAppPath() + "log4net.config"));
//xml configurator replaced by code
AppConsole = new log4net.Appender.ConsoleAppender();
AppConsole.Layout = new log4net.Layout.PatternLayout("%date{HH:mm:ss,fff} %5level [%thread] %message%n");
AppConsole.Threshold = log4net.Core.Level.Debug;

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

AppFile.File = "Service.log";
AppFile.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date;
AppFile.Threshold = log4net.Core.Level.Debug;

AppEvlog = new log4net.Appender.EventLogAppender();
AppEvlog.Layout = new log4net.Layout.PatternLayout("[%thread] %message (%logger{1})");
AppEvlog.ApplicationName = "IPserver";
AppEvlog.Threshold = log4net.Core.Level.Info;

rootLog = new log4net.Repository.Hierarchy.RootLogger(log4net.Core.Level.Info);
                       
rootLog.AddAppender(AppConsole);
rootLog.AddAppender(AppFile);
rootLog.AddAppender(AppEvlog);
//----
log = LogManager.GetLogger(typeof(IPservice));
Log.Info("Start"); // no log produced here...
rootLog.RemoveAppender(AppFile); // disable file logging
...
But after rewriting aplication doesn't create any logs….
Did I miss some settings or am I complete wrong?

Thanks for any suggestions
Radovan Raszka

Vanderkolk, John

07/27/2007 2:26 PM  

I would do something like this:

 

      log4net.Appender.IAppender[] appenders = log4net.LogManager.GetRepository().GetAppenders();

 

      for (int i = 0; i < appenders.Length; ++i)

      {

            Log4net.Appender.FileAppender appender = appenders[i] as log4net.Appender.FileAppender;

            if (appender != null && appender.Name == "RollingFile")

                  appender.Threshold = log4net.Core.Level.Off;

      }

 

Or if you want to turn all File Appenders you can take out the ‘ && appender.Name == "RollingFile"’.

 

John VanderKolk


The contents of this e-mail are intended for the named addressee only. It contains information that may be confidential. Unless you are the named addressee or an authorized designee, you may not copy or use it, or disclose it to anyone else. If you received it in error please notify us immediately and then destroy it.
 
Ron Grabowski

08/03/2007 4:51 AM  

Instead of removing the appender you could just set its threshold to OFF then when you want to enable it again you can set it back to DEBUG:

// untested
public static void SetThreshold(string appenderName, Level threshold)
{
    foreach (AppenderSkeleton appender in LogManager.GetRepository().GetAppenders())
    {
        if (appender.Name == appenderName)
        {
            appender.Threshold = threshold;
            appender.ActivateOptions();
            break;
        }
    }
}

Ron Grabowski

08/03/2007 4:53 AM  

Doh! I keep posted without reading all the messages. John's suggestion
is the same as mine except he posted it a few days earlier.

Radovan Raszka

08/03/2007 11:26 PM  
Thanks for proposal to John and Ron, it works well.
But when I tried the reverse strategy (set Threshold to OFF in config file and change to DEBUG when needed), I noticed that empty log file (Service.log in my configuration) is created (file size = 0 bytes).
Can this feature be disabled?
 
I think it would be great to add some samples of programatic configuration into SDK documentation - current documentation is completely out of any example.
Radovan

 
Vanderkolk, John

08/06/2007 10:15 PM  

That’s because of how log4net configures itself. When the repository finds a reference to a file appender in a logger that it is creating, it will automatically ask its LockingModel to create that file.  Even if your program has no intent on writing to that file log4net will still create it as soon as it knows that you might write to it. I managed to find two ways to accomplish what you want.

 

1.

 

Create a new locking model and use that as your locking model:

 

public class MyLock : log4net.Appender.FileAppender.MinimalLock

{

      public override Stream AcquireLock()

      {

            if (CurrentAppender.Threshold == log4net.Core.Level.Off)

                  return null;

            return base.AcquireLock();

      }

}

 

Now in the config file, set the threshold to start out as: <threshold value="OFF" /> and make sure you set this new LockingModel as you model: <lockingModel type="Namespace.MyLock" />. Now when your locking model is called to create the file, if the threshold is set to OFF, it will refuse. This will cause an internal exception (no way around it) but I see no reason to believe this is an invalid method.

 

2.

 

If in the config file you specify an empty string as the file name (<file value=""/>), when log4net configures itself with that appender it will throw an exception to itself and give up on creating any file for that appender, but importantly, it WILL create the appender anyway.  So if you do that then the first time that you want to log to it you can specify a file like this:

 

public void directAppenderToFile(string appender, string path)

{

      log4net.Appender.IAppender[] appenders = log4net.LogManager.GetRepository().GetAppenders();

 

      for (int i = 0; i < appenders.Length; ++i)

      {

            log4net.Appender.FileAppender curAppender = appenders[i] as log4net.Appender.FileAppender;

 

            if (curAppender != null && curAppender.Name == appender)

            {

                  curAppender.File = path;

                  curAppender.ActivateOptions();

            }

      }

}

 

I personally prefer the first method, but it’s up to you to decide which one works best for you.

 

Happy Logging,

John VanderKolk


The contents of this e-mail are intended for the named addressee only. It contains information that may be confidential. Unless you are the named addressee or an authorized designee, you may not copy or use it, or disclose it to anyone else. If you received it in error please notify us immediately and then destroy it.
Radovan Raszka

08/07/2007 12:48 PM  
Great!
I tested and used first solution, because it seems better for me (file path + name is independent on the program code).
Thanks for help
Radovan
timtas
Posts:1

08/10/2007 1:55 PM  
I added this method to my logger class, and it works. It's like the other two posted, but it's generic, which is nice.

[code]private static void DisableAppender(string appenderName) where T : AppenderSkeleton
{
IAppender[] appenders = LogManager.GetRepository().GetAppenders();
foreach (IAppender appender in appenders)
{
if (appender.Name.Equals(appenderName))
{
((T)appender).Threshold = log4net.Core.Level.Off;;
}
}
}[/code]
You are not authorized to post a reply.
Forums > Log4Net > Log4Net Mail archive > Disable/enable appender for all loggers



ActiveForums 3.7

 

 

 

 

 

 

 

 

Log4Net Dashboard

Log analysis and monitoring made easy!

Log4Net Dashboard is a log viewer that can read log statements from a variety of logging output targets.

You can download a free developer version.

  

Check it out!

On the demonstration site you can try it  with live data.demo.l4ndash.com - Try Log4Net Dashboard with live data

The mail archive is a copy of all the mail sent to the mail address: log4net-user@logging.apache.org, organized as a forum.

If you would like to participate in the mail list, send a mail to log4net-user-subscribe@logging.apache.org.

More information about the mailing list is available on: http://logging.apache.org/log4net/support.html

 

A complete topic list is available and can be viewed here (warning, it takes some time to load)

 

Copyright 2005-2008 by FaktNet AS Terms Of Use Privacy Statement