Java Code Examples for org.apache.log4j.Appender#addFilter()

The following examples show how to use org.apache.log4j.Appender#addFilter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LoggingTester.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private static void removeFilter(final Appender appender, final Filter filter) {
  Filter _filter = appender.getFilter();
  boolean _equals = Objects.equal(_filter, filter);
  if (_equals) {
    appender.clearFilters();
    appender.addFilter(filter.getNext());
  } else {
    for (Filter current = appender.getFilter(); (current != null); current = current.getNext()) {
      Filter _next = current.getNext();
      boolean _equals_1 = Objects.equal(_next, filter);
      if (_equals_1) {
        current.setNext(filter.getNext());
        return;
      }
    }
  }
}
 
Example 2
Source File: LoggingTester.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private static void removeFilter(final Appender appender, final Filter filter) {
  Filter _filter = appender.getFilter();
  boolean _equals = Objects.equal(_filter, filter);
  if (_equals) {
    appender.clearFilters();
    appender.addFilter(filter.getNext());
  } else {
    for (Filter current = appender.getFilter(); (current != null); current = current.getNext()) {
      Filter _next = current.getNext();
      boolean _equals_1 = Objects.equal(_next, filter);
      if (_equals_1) {
        current.setNext(filter.getNext());
        return;
      }
    }
  }
}
 
Example 3
Source File: HeliumBundleFactory.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private synchronized void configureLogger() {
  org.apache.log4j.Logger npmLogger = org.apache.log4j.Logger.getLogger(
      "com.github.eirslett.maven.plugins.frontend.lib.DefaultYarnRunner");
  Enumeration appenders = org.apache.log4j.Logger.getRootLogger().getAllAppenders();

  if (appenders != null) {
    while (appenders.hasMoreElements()) {
      Appender appender = (Appender) appenders.nextElement();
      appender.addFilter(new Filter() {

        @Override
        public int decide(LoggingEvent loggingEvent) {
          if (loggingEvent.getLoggerName().contains("DefaultYarnRunner")) {
            return DENY;
          } else {
            return NEUTRAL;
          }
        }
      });
    }
  }
  npmLogger.addAppender(new WriterAppender(
      new PatternLayout("%m%n"),
      out
  ));
}
 
Example 4
Source File: LogTest.java    From xenqtt with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setupBeforeClass() throws Exception {
	Logger xenqtt = Logger.getLogger("xenqtt");
	assertNotNull(xenqtt);

	Appender console = Logger.getRootLogger().getAppender("console");
	assertNotNull(console);

	console.addFilter(new Filter() {
		@Override
		public int decide(LoggingEvent event) {
			entries.add(event.getRenderedMessage());

			ThrowableInformation info = event.getThrowableInformation();
			if (info != null) {
				Throwable t = info.getThrowable();
				if (t != null) {
					entries.add(t.getMessage());
				}
			}

			return Filter.ACCEPT;
		}
	});
}
 
Example 5
Source File: Log4jAppenderTest.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Test
public void clearFilters() {
  Appender appender = getAppender();
  appender.addFilter( mock( Filter.class ) );
  appender.clearFilters();
  assertNull( appender.getFilter() );
}
 
Example 6
Source File: Log.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Link this instance to log4j
 * 
 * @param id the id for which we accept log entries
 * @param pattern a list of strings where one must be a prefix for the name to log
 */
public void link (String id, String[] pattern) {
	Appender	app = new LogAppender (this, id, pattern);

	app.addFilter (new LogFilter ());
	BasicConfigurator.configure (app);
}
 
Example 7
Source File: Log4jAppenderTest.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Test
public void addFilter() {
  Appender appender = getAppender();
  Filter filter = mock( Filter.class );
  appender.addFilter( filter );
  assertThat( appender.getFilter(), is( filter ) );
}
 
Example 8
Source File: TestSimpleFlamdexDocWriter.java    From imhotep with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void initLog4j() {
    BasicConfigurator.resetConfiguration();
    BasicConfigurator.configure();

    final Layout LAYOUT = new PatternLayout("[ %d{ISO8601} %-5p ] [%c{1}] %m%n");

    LevelRangeFilter ERROR_FILTER = new LevelRangeFilter();
    ERROR_FILTER.setLevelMin(Level.ERROR);
    ERROR_FILTER.setLevelMax(Level.FATAL);

    // everything including ERROR
    final Appender STDOUT = new ConsoleAppender(LAYOUT, ConsoleAppender.SYSTEM_OUT);

    // just things <= ERROR
    final Appender STDERR = new ConsoleAppender(LAYOUT, ConsoleAppender.SYSTEM_ERR);
    STDERR.addFilter(ERROR_FILTER);

    final Logger ROOT_LOGGER = Logger.getRootLogger();

    ROOT_LOGGER.removeAllAppenders();

    ROOT_LOGGER.setLevel(Level.WARN); // don't care about higher

    ROOT_LOGGER.addAppender(STDOUT);
    ROOT_LOGGER.addAppender(STDERR);
}
 
Example 9
Source File: AbstractFTGSMergerCase.java    From imhotep with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void initLog4j() {
    BasicConfigurator.resetConfiguration();
    BasicConfigurator.configure();

    final Layout LAYOUT = new PatternLayout("[ %d{ISO8601} %-5p ] [%c{1}] %m%n");

    LevelRangeFilter ERROR_FILTER = new LevelRangeFilter();
    ERROR_FILTER.setLevelMin(Level.ERROR);
    ERROR_FILTER.setLevelMax(Level.FATAL);

    // everything including ERROR
    final Appender STDOUT = new ConsoleAppender(LAYOUT, ConsoleAppender.SYSTEM_OUT);

    // just things <= ERROR
    final Appender STDERR = new ConsoleAppender(LAYOUT, ConsoleAppender.SYSTEM_ERR);
    STDERR.addFilter(ERROR_FILTER);

    final Logger ROOT_LOGGER = Logger.getRootLogger();

    ROOT_LOGGER.removeAllAppenders();

    ROOT_LOGGER.setLevel(Level.WARN); // don't care about higher

    ROOT_LOGGER.addAppender(STDOUT);
    ROOT_LOGGER.addAppender(STDERR);
}
 
Example 10
Source File: TestLocalImhotepServiceCore.java    From imhotep with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void initLog4j() {
    BasicConfigurator.resetConfiguration();
    BasicConfigurator.configure();

    final Layout LAYOUT = new PatternLayout("[ %d{ISO8601} %-5p ] [%c{1}] %m%n");

    LevelRangeFilter ERROR_FILTER = new LevelRangeFilter();
    ERROR_FILTER.setLevelMin(Level.ERROR);
    ERROR_FILTER.setLevelMax(Level.FATAL);

    // everything including ERROR
    final Appender STDOUT = new ConsoleAppender(LAYOUT, ConsoleAppender.SYSTEM_OUT);

    // just things <= ERROR
    final Appender STDERR = new ConsoleAppender(LAYOUT, ConsoleAppender.SYSTEM_ERR);
    STDERR.addFilter(ERROR_FILTER);

    final Logger ROOT_LOGGER = Logger.getRootLogger();

    ROOT_LOGGER.removeAllAppenders();

    ROOT_LOGGER.setLevel(Level.WARN); // don't care about higher

    ROOT_LOGGER.addAppender(STDOUT);
    ROOT_LOGGER.addAppender(STDERR);
}
 
Example 11
Source File: LevelMatchFilterTestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void deny() throws Exception {
  
  // set up appender
  Layout layout = new SimpleLayout();
  Appender appender = new FileAppender(layout, DENY_FILE, false);
  
  // create LevelMatchFilter, set to deny matches
  LevelMatchFilter matchFilter = new LevelMatchFilter();
  matchFilter.setAcceptOnMatch(false);
 
   // attach match filter to appender
  appender.addFilter(matchFilter);
         
  // set appender on root and set level to debug
  root.addAppender(appender);
  root.setLevel(Level.TRACE);
  
  Level[] levelArray = new Level[] {Level.TRACE, Level.DEBUG, Level.INFO, Level.WARN,
		      Level.ERROR, Level.FATAL};
  for (int x = 0; x < levelArray.length; x++) {
    // set the level to match
    matchFilter.setLevelToMatch(levelArray[x].toString());
    common("pass " + x + "; filter set to deny only " + levelArray[x].toString()
            + " msgs");
  }
  
  Transformer.transform(DENY_FILE, DENY_FILTERED, new LineNumberFilter());
  assertTrue(Compare.compare(DENY_FILTERED, DENY_WITNESS));
}
 
Example 12
Source File: LevelMatchFilterTestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void accept() throws Exception {
  
  // set up appender
  Layout layout = new SimpleLayout();
  Appender appender = new FileAppender(layout, ACCEPT_FILE, false);
  
  // create LevelMatchFilter
  LevelMatchFilter matchFilter = new LevelMatchFilter();
 
   // attach match filter to appender
  appender.addFilter(matchFilter);
 
  // attach DenyAllFilter to end of filter chain to deny neutral
  // (non matching) messages
  appender.addFilter(new DenyAllFilter());
      
  // set appender on root and set level to debug
  root.addAppender(appender);
  root.setLevel(Level.TRACE);
  
  Level[] levelArray = new Level[] {Level.TRACE, Level.DEBUG, Level.INFO, Level.WARN, 
		      Level.ERROR, Level.FATAL};
  for (int x = 0; x < levelArray.length; x++) {
    // set the level to match
    matchFilter.setLevelToMatch(levelArray[x].toString());
    common("pass " + x + "; filter set to accept only " 
    + levelArray[x].toString() + " msgs");
  }
  
  Transformer.transform(ACCEPT_FILE, ACCEPT_FILTERED, new LineNumberFilter());
  assertTrue(Compare.compare(ACCEPT_FILTERED, ACCEPT_WITNESS));
}
 
Example 13
Source File: DOMConfigurator.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    Used internally to parse a filter element.
  */
 protected
 void parseFilters(Element element, Appender appender) {
   String clazz = subst(element.getAttribute(CLASS_ATTR));
   Filter filter = (Filter) OptionConverter.instantiateByClassName(clazz,
                                               Filter.class, null);
   
   if(filter != null) {
     PropertySetter propSetter = new PropertySetter(filter);
     NodeList children = element.getChildNodes();
     final int length 	= children.getLength();

     for (int loop = 0; loop < length; loop++) {
Node currentNode = children.item(loop);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
  Element currentElement = (Element) currentNode;
  String tagName = currentElement.getTagName();
  if(tagName.equals(PARAM_TAG)) {
           setParameter(currentElement, propSetter);
  } else {
           quietParseUnrecognizedElement(filter, currentElement, props);
     }
}
     }
     propSetter.activate();
     LogLog.debug("Adding filter of type ["+filter.getClass()
	   +"] to appender named ["+appender.getName()+"].");
     appender.addFilter(filter);
   }    
 }
 
Example 14
Source File: DBase.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public DBDatasource () {
	cache = new HashMap<>();
	seen = new HashSet<>();
	log = new Log ("jdbc", Log.INFO);

	Appender	app = new DBaseAppender (log);

	app.addFilter (new DBaseFilter ());
	BasicConfigurator.configure (app);
}
 
Example 15
Source File: GridTestLog4jLogger.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Creates console appender with some reasonable default logging settings.
 *
 * @param maxLevel Max logging level.
 * @return New console appender.
 */
private Appender createConsoleAppender(Level maxLevel) {
    String fmt = "[%d{ISO8601}][%-5p][%t][%c{1}] %m%n";

    // Configure output that should go to System.out
    Appender app = new ConsoleAppender(new PatternLayout(fmt), ConsoleAppender.SYSTEM_OUT);

    LevelRangeFilter lvlFilter = new LevelRangeFilter();

    lvlFilter.setLevelMin(Level.TRACE);
    lvlFilter.setLevelMax(maxLevel);

    app.addFilter(lvlFilter);

    return app;
}
 
Example 16
Source File: Log4JLogger.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Creates console appender with some reasonable default logging settings.
 *
 * @param maxLevel Max logging level.
 * @return New console appender.
 */
private Appender createConsoleAppender(Level maxLevel) {
    String fmt = "[%d{ISO8601}][%-5p][%t][%c{1}] %m%n";

    // Configure output that should go to System.out
    Appender app = new ConsoleAppender(new PatternLayout(fmt), ConsoleAppender.SYSTEM_OUT);

    LevelRangeFilter lvlFilter = new LevelRangeFilter();

    lvlFilter.setLevelMin(Level.TRACE);
    lvlFilter.setLevelMax(maxLevel);

    app.addFilter(lvlFilter);

    return app;
}
 
Example 17
Source File: RemoteLoggingConfigurator.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings( "unchecked")
public void apply() {

    /*
     * This code is run on remote agent's side
     */

    if (needsToConfigureDbAppender) {
        //first get all appenders in the root category and apply the filter
        //which will deny logging of system events
        Logger rootLogger = Logger.getRootLogger();
        Enumeration<Appender> appenders = rootLogger.getAllAppenders();
        while (appenders.hasMoreElements()) {
            Appender appender = appenders.nextElement();
            if (! (appender instanceof AbstractDbAppender)) {
                // apply this filter on all appenders which are not coming from ATS
                appender.addFilter(new NoSystemLevelEventsFilter());
            }
        }

        //attach the appender to the logging system
        Category log;
        if ("root".equals(appenderLogger)) {
            log = Logger.getRootLogger();
        } else {
            log = Logger.getLogger(appenderLogger);
        }

        log.setLevel(Level.toLevel(appenderConfiguration.getLoggingThreshold().toInt()));

        final String caller = ThreadsPerCaller.getCaller();

        //create the new appender
        PassiveDbAppender attachedAppender = new PassiveDbAppender(caller);
        attachedAppender.setAppenderConfig(appenderConfiguration);
        //use a default pattern, as we log in the db
        attachedAppender.setLayout(new PatternLayout("%c{2}: %m%n"));
        attachedAppender.activateOptions();

        log.addAppender(attachedAppender);
    }

    if (needsToConfigureUserLoggers) {
        for (Entry<String, Integer> userLogger : otherLoggerLevels.entrySet()) {
            /* 
             * We want to set the level of this logger.
             * It is not important if this logger is already attached to log4j system or 
             * not as the next code will obtain it(in case logger exists) or will create it 
             * and then will set its level
             */
            Logger.getLogger(userLogger.getKey())
                  .setLevel(Level.toLevel(userLogger.getValue()));
        }
    }
}