Java Code Examples for org.apache.log4j.Logger#getAllAppenders()

The following examples show how to use org.apache.log4j.Logger#getAllAppenders() . 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: ConfigManager.java    From serve with Apache License 2.0 7 votes vote down vote up
private void enableAsyncLogging(Logger logger) {
    AsyncAppender asyncAppender = new AsyncAppender();

    @SuppressWarnings("unchecked")
    Enumeration<Appender> en = logger.getAllAppenders();
    while (en.hasMoreElements()) {
        Appender appender = en.nextElement();
        if (appender instanceof AsyncAppender) {
            // already async
            return;
        }

        logger.removeAppender(appender);
        asyncAppender.addAppender(appender);
    }
    logger.addAppender(asyncAppender);
}
 
Example 2
Source File: FailedMessagesLogger.java    From atlas with Apache License 2.0 6 votes vote down vote up
/**
 * Get the root logger file location under which the failed log messages will be written.
 *
 * Since this class is used in Hooks which run within JVMs of other components like Hive,
 * we want to write the failed messages file under the same location as where logs from
 * the host component are saved. This method attempts to get such a location from the
 * root logger's appenders. It will work only if at least one of the appenders is a {@link FileAppender}
 *
 * @return directory under which host component's logs are stored.
 */
private String getRootLoggerDirectory() {
    String      rootLoggerDirectory = null;
    Logger      rootLogger          = Logger.getRootLogger();
    Enumeration allAppenders        = rootLogger.getAllAppenders();

    if (allAppenders != null) {
        while (allAppenders.hasMoreElements()) {
            Appender appender = (Appender) allAppenders.nextElement();

            if (appender instanceof FileAppender) {
                FileAppender fileAppender   = (FileAppender) appender;
                String       rootLoggerFile = fileAppender.getFile();

                rootLoggerDirectory = rootLoggerFile != null ? new File(rootLoggerFile).getParent() : null;
                break;
            }
        }
    }
    return rootLoggerDirectory;
}
 
Example 3
Source File: LocalSystemOperations.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
public void setAtsDbAppenderThreshold( Level threshold ) {

        Logger rootLogger = Logger.getRootLogger();
        Enumeration<Appender> appenders = rootLogger.getAllAppenders();
        while (appenders.hasMoreElements()) {
            Appender appender = appenders.nextElement();
            if (appender != null) {
                if (appender.getClass().getName().equals("com.axway.ats.log.appenders.ActiveDbAppender")) {
                    ((AppenderSkeleton) appender).setThreshold(threshold);
                }
                if (appender.getClass().getName().equals("com.axway.ats.log.appenders.PassiveDbAppender")) {
                    String callerId = ThreadsPerCaller.getCaller();
                    String passiveDbAppenderCaller = (String) ReflectionUtils.getFieldValue(appender, "caller", true);
                    if (callerId != null && callerId.equals(passiveDbAppenderCaller)) {
                        ((AppenderSkeleton) appender).setThreshold(threshold);
                    }
                }
            }
        }
    }
 
Example 4
Source File: TaskLog.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public synchronized static void syncLogs(String logLocation, 
                                         TaskAttemptID taskid,
                                         boolean isCleanup) 
throws IOException {
  System.out.flush();
  System.err.flush();
  Enumeration<Logger> allLoggers = LogManager.getCurrentLoggers();
  while (allLoggers.hasMoreElements()) {
    Logger l = allLoggers.nextElement();
    Enumeration<Appender> allAppenders = l.getAllAppenders();
    while (allAppenders.hasMoreElements()) {
      Appender a = allAppenders.nextElement();
      if (a instanceof TaskLogAppender) {
        ((TaskLogAppender)a).flush();
      }
    }
  }
  if (currentTaskid != taskid) {
    currentTaskid = taskid;
    resetPrevLengths(logLocation);
  }
  writeToIndexFile(logLocation, isCleanup);
}
 
Example 5
Source File: CoasterService.java    From swift-k with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
protected static Appender getFileAppender() {
    Logger root = Logger.getRootLogger();
    Enumeration e = root.getAllAppenders();
    while (e.hasMoreElements()) {
        Appender a = (Appender) e.nextElement();
        if (a instanceof FileAppender) {
            return a;
        }
        if (a instanceof AsyncAppender) {
            // likely this is running in a JVM in which
            // the file appender has been replaced with
            // an async appender, so don't mess with things
            return null;
        }
    }
    logger.warn("Could not find a file appender to configure");
    return null;
}
 
Example 6
Source File: Log4jHookProxy.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private LinkedList<LogProfileInfo> figureoutLogConfiguration(Logger Logger, String appid) {
    
    LinkedList<LogProfileInfo> logProfiles = new LinkedList<LogProfileInfo>();

    Enumeration<Appender> appenders = Logger.getAllAppenders();
    while (appenders != null && appenders.hasMoreElements()) {

        Appender appender = appenders.nextElement();
        if (appender instanceof FileAppender) {
            logProfiles.add(getAppenderInfo((FileAppender)appender, appid));
        }
        else if(appender instanceof AsyncAppender) {
            Enumeration<Appender> ads = ((AsyncAppender) appender).getAllAppenders();
            while(ads != null && ads.hasMoreElements()) {
                Appender ap = ads.nextElement();
                if(ap instanceof FileAppender) {
                    logProfiles.add(getAppenderInfo((FileAppender)ap, appid));
                }
            }
        }
    }
    
    return logProfiles;
}
 
Example 7
Source File: LoggerUtil.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list names of the appenders
 * @param logger Logger to list appender for, if null, use root logger
 * @return Names of the appenders
 */
public static List<String> getAppendersNames(Logger logger)
{
  if (logger == null) {
    logger = LogManager.getRootLogger();
  }
  Enumeration enumeration = logger.getAllAppenders();
  List<String> names = new LinkedList<>();
  while (enumeration.hasMoreElements()) {
    names.add(((Appender)enumeration.nextElement()).getName());
  }
  return names;
}
 
Example 8
Source File: LoggerUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list names of the appenders
 * @param logger Logger to list appender for, if null, use root logger
 * @return Names of the appenders
 */
public static List<String> getAppendersNames(Logger logger)
{
  if (logger == null) {
    logger = LogManager.getRootLogger();
  }
  Enumeration enumeration = logger.getAllAppenders();
  List<String> names = new LinkedList<>();
  while (enumeration.hasMoreElements()) {
    names.add(((Appender)enumeration.nextElement()).getName());
  }
  return names;
}
 
Example 9
Source File: MainGUI.java    From EccPlayground with Apache License 2.0 5 votes vote down vote up
/**
    * @param args
    *            the command line arguments
    */
   public static void main(String args[]) {
/* Set the Nimbus look and feel */
// <editor-fold defaultstate="collapsed"
// desc=" Look and feel setting code (optional) ">
/*
 * If Nimbus (introduced in Java SE 6) is not available, stay with the
 * default look and feel. For details see
 * http://download.oracle.com/javase
 * /tutorial/uiswing/lookandfeel/plaf.html
 */
try {
    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
	if ("Nimbus".equals(info.getName())) {
	    javax.swing.UIManager.setLookAndFeel(info.getClassName());
	    break;
	}
    }
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
    LOG.warn(ex.getLocalizedMessage(), ex);
}

Logger log = Logger.getRootLogger();

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
	new MainGUI().setVisible(true);
    }
});

Enumeration app = log.getAllAppenders();
while (app.hasMoreElements()) {
    Appender a = (Appender) app.nextElement();
}
   }
 
Example 10
Source File: SFTPFileSystemLoggingTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
private static List<Appender> getAllAppenders(Logger l) {
    List<Appender> appenders = new ArrayList<>();
    for (@SuppressWarnings("unchecked") Enumeration<Appender> e = l.getAllAppenders(); e.hasMoreElements(); ) {
        appenders.add(e.nextElement());
    }
    return appenders;
}
 
Example 11
Source File: TestAuditLogs.java    From big-c with Apache License 2.0 5 votes vote down vote up
private void verifyAuditLogsCheckPattern(boolean expectSuccess, int ndupe, Pattern pattern)
    throws IOException {
  // Turn off the logs
  Logger logger = ((Log4JLogger) FSNamesystem.auditLog).getLogger();
  logger.setLevel(Level.OFF);

  // Close the appenders and force all logs to be flushed
  Enumeration<?> appenders = logger.getAllAppenders();
  while (appenders.hasMoreElements()) {
    Appender appender = (Appender)appenders.nextElement();
    appender.close();
  }

  BufferedReader reader = new BufferedReader(new FileReader(auditLogFile));
  String line = null;
  boolean ret = true;
  boolean patternMatches = false;

  try {
      for (int i = 0; i < ndupe; i++) {
        line = reader.readLine();
        assertNotNull(line);
        patternMatches |= pattern.matcher(line).matches();
        ret &= successPattern.matcher(line).matches();
      }
      assertNull("Unexpected event in audit log", reader.readLine());
      assertTrue("Expected audit event not found in audit log", patternMatches);
      assertTrue("Expected success=" + expectSuccess, ret == expectSuccess);
    } finally {
      reader.close();
    }
}
 
Example 12
Source File: TestAuditLogs.java    From big-c with Apache License 2.0 5 votes vote down vote up
private void verifyAuditLogsRepeat(boolean expectSuccess, int ndupe)
    throws IOException {
  // Turn off the logs
  Logger logger = ((Log4JLogger) FSNamesystem.auditLog).getLogger();
  logger.setLevel(Level.OFF);

  // Close the appenders and force all logs to be flushed
  Enumeration<?> appenders = logger.getAllAppenders();
  while (appenders.hasMoreElements()) {
    Appender appender = (Appender)appenders.nextElement();
    appender.close();
  }

  BufferedReader reader = new BufferedReader(new FileReader(auditLogFile));
  String line = null;
  boolean ret = true;

  try {
    for (int i = 0; i < ndupe; i++) {
      line = reader.readLine();
      assertNotNull(line);
      assertTrue("Expected audit event not found in audit log",
          auditPattern.matcher(line).matches());
      ret &= successPattern.matcher(line).matches();
    }
    assertNull("Unexpected event in audit log", reader.readLine());
    assertTrue("Expected success=" + expectSuccess, ret == expectSuccess);
  } finally {
    reader.close();
  }
}
 
Example 13
Source File: CoasterPersistentService.java    From swift-k with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
protected static Appender getAppender(Class cls) {
    Logger root = Logger.getRootLogger();
    Enumeration e = root.getAllAppenders();
    while (e.hasMoreElements()) {
        Appender a = (Appender) e.nextElement();
        if (cls.isAssignableFrom(a.getClass())) {
            return a;
        }
    }
    return null;
}
 
Example 14
Source File: Loader.java    From swift-k with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
protected static Appender getAppender(Class cls) {
    Logger root = Logger.getRootLogger();
    Enumeration e = root.getAllAppenders();
    while (e.hasMoreElements()) {
        Appender a = (Appender) e.nextElement();
        if (cls.isAssignableFrom(a.getClass())) {
            return a;
        }
    }
    return null;
}
 
Example 15
Source File: TestAuditLogs.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private void verifyAuditLogsCheckPattern(boolean expectSuccess, int ndupe, Pattern pattern)
    throws IOException {
  // Turn off the logs
  Logger logger = ((Log4JLogger) FSNamesystem.auditLog).getLogger();
  logger.setLevel(Level.OFF);

  // Close the appenders and force all logs to be flushed
  Enumeration<?> appenders = logger.getAllAppenders();
  while (appenders.hasMoreElements()) {
    Appender appender = (Appender)appenders.nextElement();
    appender.close();
  }

  BufferedReader reader = new BufferedReader(new FileReader(auditLogFile));
  String line = null;
  boolean ret = true;
  boolean patternMatches = false;

  try {
      for (int i = 0; i < ndupe; i++) {
        line = reader.readLine();
        assertNotNull(line);
        patternMatches |= pattern.matcher(line).matches();
        ret &= successPattern.matcher(line).matches();
      }
      assertNull("Unexpected event in audit log", reader.readLine());
      assertTrue("Expected audit event not found in audit log", patternMatches);
      assertTrue("Expected success=" + expectSuccess, ret == expectSuccess);
    } finally {
      reader.close();
    }
}
 
Example 16
Source File: RMStarter.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Wrap existing appenders configured for the root logger in AsyncAppenders
 */
public static void overrideAppenders() {
    if (PAResourceManagerProperties.LOG4J_ASYNC_APPENDER_ENABLED.getValueAsBoolean()) {
        Logger rootLogger = Logger.getRootLogger();
        Enumeration<?> en = rootLogger.getAllAppenders();
        if (en != null) {
            List<AsyncAppender> newAppenders = new ArrayList<>();
            List<String> appendersToRemove = new ArrayList<>();
            int index = 0;
            while (en.hasMoreElements()) {
                Appender app = (Appender) en.nextElement();
                if (app != null && !(app instanceof AsyncAppender)) {
                    AsyncAppender asyncAppender = new AsyncAppender();
                    asyncAppender.setName("MainAsyncAppender_" + index);
                    asyncAppender.setBufferSize(PAResourceManagerProperties.LOG4J_ASYNC_APPENDER_BUFFER_SIZE.getValueAsInt());
                    asyncAppender.addAppender(app);
                    newAppenders.add(asyncAppender);
                    appendersToRemove.add(app.getName());
                    index++;
                }
            }
            for (String appenderName : appendersToRemove) {
                rootLogger.removeAppender(appenderName);
            }
            for (Appender newAppender : newAppenders) {
                rootLogger.addAppender(newAppender);
            }
        }
    }
}
 
Example 17
Source File: TaskLog.java    From RDFS with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public synchronized static void syncLogs(TaskAttemptID firstTaskid, 
                                         TaskAttemptID taskid,
                                         boolean isCleanup) 
throws IOException {
  System.out.flush();
  System.err.flush();
  Enumeration<Logger> allLoggers = LogManager.getCurrentLoggers();
  while (allLoggers.hasMoreElements()) {
    Logger l = allLoggers.nextElement();
    Enumeration<Appender> allAppenders = l.getAllAppenders();
    while (allAppenders.hasMoreElements()) {
      Appender a = allAppenders.nextElement();
      if (a instanceof TaskLogAppender) {
        ((TaskLogAppender)a).flush();
      }
    }
  }
  // set start and end
  for (LogName logName : LOGS_TRACKED_BY_INDEX_FILES) {
    if (currentTaskid != taskid) {
      // Set start = current-end
      logLengths.get(logName)[0] =
          Long.valueOf(getTaskLogFile(firstTaskid, logName).length());
    }
    // Set current end
    logLengths.get(logName)[1] =
        Long.valueOf(getTaskLogFile(firstTaskid, logName).length());
  }
  if (currentTaskid != taskid) {
    if (currentTaskid != null) {
      LOG.info("Starting logging for a new task " + taskid
          + " in the same JVM as that of the first task " + firstTaskid);
    }
    currentTaskid = taskid;
  }
  writeToIndexFile(firstTaskid, taskid, isCleanup, logLengths);
}
 
Example 18
Source File: LogWriter.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public boolean close() {
  boolean isNotEmbedded = true;
  try {
    // Close all appenders only if we are not embedded (ie. running a report in BA Server
    // that has a PDI data source is considered embedded)
    Logger logger = Logger.getLogger( STRING_PENTAHO_DI_LOGGER_NAME );
    Enumeration<?> appenders = logger.getAllAppenders();
    while ( appenders.hasMoreElements() ) {
      final Appender appender = (Appender) appenders.nextElement();
      // Check to see if we have registered BA Server appenders
      if ( ( appender.getName().compareTo( STRING_PENTAHO_BASERVER_FILE_APPENDER ) == 0 )
        || ( appender.getName().compareTo( STRING_PENTAHO_BASERVER_CONSOLE_APPENDER ) == 0 ) ) {
        isNotEmbedded = false;
        break;
      }
    }

    // If we are not embedded, we can safely close all appenders.
    if ( isNotEmbedded == true ) {
      pentahoLogger.removeAllAppenders();
      LogWriter.unsetLogWriter();
    }
  } catch ( Exception e ) {
    isNotEmbedded = false;
  }

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

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

    /*
     * The outer code will call this method when the "needs applying" method return true.
     * 
     * Currently we could come here because of 2 reasons:
     *  - the DB appenders must be reconfigured
     *  - the user loggers must be reconfigured
     */

    if (appenderLogger != null && needsToConfigureDbAppender) {
        // there is a DB appender and it is out-of-date

        //remove 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();

            //remove the filter
            //FIXME:This is very risky, as someone may have added other filters
            //the current implementation of the filter chain in log4j will not allow
            //us to easily remove a single filter
            appender.clearFilters();
        }

        Category log;
        if ("root".equals(appenderLogger)) {
            log = Logger.getRootLogger();
        } else {
            log = Logger.getLogger(appenderLogger);
        }

        Appender dbAppender = PassiveDbAppender.getCurrentInstance(ThreadsPerCaller.getCaller());
        if (dbAppender != null) {
            //close the appender
            dbAppender.close();

            //remove it
            log.removeAppender(dbAppender);
        }
    }

    // in case we must reconfigure the custom loggers, here we should remove them from log4j, 
    // but log4j does not provide a way to do it - so we do nothing here 
}
 
Example 20
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()));
        }
    }
}