org.apache.log4j.Appender Java Examples

The following examples show how to use org.apache.log4j.Appender. 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: Log4jLoggerAdapter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Log4jLoggerAdapter() {
	try {
		org.apache.log4j.Logger logger = LogManager.getRootLogger();
           if (logger != null) {
               Enumeration<Appender> appenders = logger.getAllAppenders();
               if (appenders != null) {
                   while (appenders.hasMoreElements()) {
                       Appender appender = appenders.nextElement();
                       if (appender instanceof FileAppender) {
                           FileAppender fileAppender = (FileAppender)appender;
                           String filename = fileAppender.getFile();
                           file = new File(filename);
                           break;
                       }
                   }
               }
           }
       } catch (Throwable t) {
       }
}
 
Example #2
Source File: Clear.java    From qiniu-logging-plugin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Before
public void tearUp() {
    Appender appender = org.apache.log4j.Logger.getRootLogger().getAppender("qiniu");
    Log4jQiniuAppender qiniuAppender = (Log4jQiniuAppender) appender;

    this.pipelineHost = qiniuAppender.getPipelineHost();
    this.logdbHost = qiniuAppender.getLogdbHost();
    this.accessKey = qiniuAppender.getAccessKey();
    this.secretKey = qiniuAppender.getSecretKey();
    this.workflowName = qiniuAppender.getWorkflowName();
    this.pipelineRepo = qiniuAppender.getPipelineRepo();
    this.logdbRepo = qiniuAppender.getLogdbRepo();
    this.exportName = String.format("%s_export_to_%s", this.pipelineRepo, this.logdbRepo);

    Auth auth = Auth.create(this.accessKey, this.secretKey);
    PandoraClient client = new PandoraClientImpl(auth);
    this.pipelineClient = new PipelineClient(client, this.pipelineHost);
    this.logDBClient = new LogDBClient(client, this.logdbHost);
}
 
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: ModePathPrefixMerging.java    From tasmo with Apache License 2.0 6 votes vote down vote up
@BeforeClass
    public void logger() {
        String PATTERN = "%t %m%n";

        Enumeration allAppenders = LogManager.getRootLogger().getAllAppenders();
        while (allAppenders.hasMoreElements()) {
            Appender appender = (Appender) allAppenders.nextElement();
            appender.setLayout(new PatternLayout(PATTERN));
        }
        //if (verbose) {
        LogManager.getLogger("com.jivesoftware.os.tasmo.lib").setLevel(Level.TRACE);
        LogManager.getLogger("com.jivesoftware.os.tasmo.lib.TasmoViewModel").setLevel(Level.TRACE);
//            LogManager.getLogger("com.jivesoftware.os.tasmo.lib.concur.ConcurrencyAndExistanceCommitChange").setLevel(Level.TRACE);
//            LogManager.getLogger("com.jivesoftware.os.tasmo.reference.lib.ReferenceStore").setLevel(Level.TRACE);
//            LogManager.getLogger("com.jivesoftware.os.tasmo.view.reader.service.writer.WriteToViewValueStore").setLevel(Level.TRACE);
//        } else {
//            LogManager.getRootLogger().setLevel(Level.OFF);
//        }
    }
 
Example #5
Source File: TimelineMetricConfiguration.java    From ambari-metrics with Apache License 2.0 6 votes vote down vote up
public String getDefaultMetricsSinkDir() {
  String dirPath = metricsConf.get(DEFAULT_EXTERNAL_SINK_DIR);
  if (dirPath == null) {
    // Only one logger at the time of writing
    Appender appender = (Appender) Logger.getRootLogger().getAllAppenders().nextElement();
    if (appender instanceof FileAppender) {
      File f = new File(((FileAppender) appender).getFile());
      if (f.exists()) {
        dirPath = f.getParent();
      } else {
        dirPath = "/tmp";
      }
    }
  }

  return dirPath;
}
 
Example #6
Source File: StdOutErrLog.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public static void tieSystemOutAndErrToLog()
{

  org.apache.log4j.Logger rootLogger = org.apache.log4j.Logger.getRootLogger();
  Appender appender = rootLogger.getAppender(DT_LOG_APPENDER);
  if (appender instanceof RollingFileAppender) {
    RollingFileAppender rfa = (RollingFileAppender)appender;
    if (rfa.getFile() == null || rfa.getFile().isEmpty()) {
      rfa.setFile(System.getProperty(DT_LOGDIR));
      rfa.activateOptions();
    }
  } else if (appender != null) {
    logger.warn("found appender {} instead of RollingFileAppender", appender);
  }

  LoggerUtil.addAppenders();
  System.setOut(createLoggingProxy(System.out));
  System.setErr(createLoggingProxy(System.err));
}
 
Example #7
Source File: RewriteAppenderBuilder.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private <T extends Log4j1Configuration> Appender createAppender(String name, String level,
        String[] appenderRefs, RewritePolicy policy, Filter filter, T configuration) {
    org.apache.logging.log4j.Level logLevel = OptionConverter.convertLevel(level,
            org.apache.logging.log4j.Level.TRACE);
    AppenderRef[] refs = new AppenderRef[appenderRefs.length];
    int index = 0;
    for (String appenderRef : appenderRefs) {
        refs[index++] = AppenderRef.createAppenderRef(appenderRef, logLevel, null);
    }
    org.apache.logging.log4j.core.Filter rewriteFilter = buildFilters(level, filter);
    org.apache.logging.log4j.core.appender.rewrite.RewritePolicy rewritePolicy;
    if (policy instanceof RewritePolicyWrapper) {
        rewritePolicy = ((RewritePolicyWrapper) policy).getPolicy();
    } else {
        rewritePolicy = new RewritePolicyAdapter(policy);
    }
    return new AppenderWrapper(RewriteAppender.createAppender(name, true, refs, configuration,
            rewritePolicy, rewriteFilter));
}
 
Example #8
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 #9
Source File: Log4jLoggerAdapter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Log4jLoggerAdapter() {
	try {
		org.apache.log4j.Logger logger = LogManager.getRootLogger();
           if (logger != null) {
               Enumeration<Appender> appenders = logger.getAllAppenders();
               if (appenders != null) {
                   while (appenders.hasMoreElements()) {
                       Appender appender = appenders.nextElement();
                       if (appender instanceof FileAppender) {
                           FileAppender fileAppender = (FileAppender)appender;
                           String filename = fileAppender.getFile();
                           file = new File(filename);
                           break;
                       }
                   }
               }
           }
       } catch (Throwable t) {
       }
}
 
Example #10
Source File: LogPageHandler.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public LogPageHandler() {
    try {
		org.apache.log4j.Logger logger = LogManager.getRootLogger();
        if (logger != null) {
            Enumeration<Appender> appenders = logger.getAllAppenders();
            if (appenders != null) {
                while (appenders.hasMoreElements()) {
                    Appender appender = appenders.nextElement();
                    if (appender instanceof FileAppender) {
                        FileAppender fileAppender = (FileAppender)appender;
                        String filename = fileAppender.getFile();
                        file = new File(filename);
                        break;
                    }
                }
            }
        }
    } catch (Throwable t) {
    }
   }
 
Example #11
Source File: XmlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Used internally to parse an {@link ErrorHandler} element.
 */
private void parseErrorHandler(Element element, Appender appender) {
    ErrorHandler eh = (ErrorHandler) OptionConverter.instantiateByClassName(
            subst(element.getAttribute(CLASS_ATTR)),
            ErrorHandler.class,
            null);

    if (eh != null) {
        eh.setAppender(appender);

        PropertySetter propSetter = new PropertySetter(eh);
        forEachElement(element.getChildNodes(), (currentElement) -> {
            String tagName = currentElement.getTagName();
            if (tagName.equals(PARAM_TAG)) {
                setParameter(currentElement, propSetter);
            }
        });
        propSetter.activate();
        appender.setErrorHandler(eh);
    }
}
 
Example #12
Source File: LogUtilities.java    From render with GNU General Public License v2.0 6 votes vote down vote up
public static void setupExecutorLog4j(final String context,
                                      final String rootLoggerName) {

    final Logger logger = LogManager.getLogger(rootLoggerName);

    for (final Enumeration e = LogManager.getRootLogger().getAllAppenders(); e.hasMoreElements(); ) {
        final Appender a = (Appender) e.nextElement();
        if (a instanceof ConsoleAppender) {
            final Layout layout = a.getLayout();
            if (layout instanceof PatternLayout) {
                final PatternLayout patternLayout = (PatternLayout) layout;
                final String conversionPattern = "%d{ISO8601} [%t] [%X{context}] %-5p [%c] %m%n";
                if (! conversionPattern.equals(patternLayout.getConversionPattern())) {
                    a.setLayout(new PatternLayout(conversionPattern));
                }
            }
        }
    }

    MDC.put("context", context);

    logger.setLevel(Level.DEBUG);
}
 
Example #13
Source File: AsyncAppenderBuilder.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public Appender parseAppender(final String name, final String appenderPrefix, final String layoutPrefix,
        final String filterPrefix, final Properties props, final PropertiesConfiguration configuration) {
    String appenderRef = getProperty(APPENDER_REF_TAG);
    boolean blocking = getBooleanProperty(BLOCKING_PARAM);
    boolean includeLocation = getBooleanProperty(INCLUDE_LOCATION_PARAM);
    String level = getProperty(THRESHOLD_PARAM);
    int bufferSize = getIntegerProperty(BUFFER_SIZE_PARAM, 1024);
    if (appenderRef == null) {
        LOGGER.warn("No appender references configured for AsyncAppender {}", name);
        return null;
    }
    Appender appender = configuration.parseAppender(props, appenderRef);
    if (appender == null) {
        LOGGER.warn("Cannot locate Appender {}", appenderRef);
        return null;
    }
    return createAppender(name, level, new String[] {appenderRef}, blocking, bufferSize, includeLocation,
            configuration);
}
 
Example #14
Source File: LoggerUtil.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
/**
 * Adds Logger Appender to a specified logger
 * @param logger Logger to add appender to, if null, use root logger
 * @param name Appender name
 * @param properties Appender properties
 * @return True if the appender has been added successfully
 */
public static boolean addAppender(Logger logger, String name, Properties properties)
{
  if (logger == null) {
    logger = LogManager.getRootLogger();
  }
  if (getAppendersNames(logger).contains(name)) {
    LoggerUtil.logger.warn("A logger appender with the name '{}' exists. Cannot add a new logger appender with the same name", name);
  } else {
    try {
      Method method = PropertyConfigurator.class.getDeclaredMethod("parseAppender", Properties.class, String.class);
      method.setAccessible(true);
      Appender appender = (Appender)method.invoke(new PropertyConfigurator(), properties, name);
      if (appender == null) {
        LoggerUtil.logger.warn("Cannot add a new logger appender. Name: {}, Properties: {}", name, properties);
      } else {
        logger.addAppender(appender);
        return true;
      }
    } catch (Exception ex) {
      LoggerUtil.logger.warn("Cannot add a new logger appender. Name: {}, Properties: {}", name, properties, ex);
    }
  }
  return false;
}
 
Example #15
Source File: XmlConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Used internally to parse an {@link ErrorHandler} element.
 */
private void parseErrorHandler(Element element, Appender appender) {
    ErrorHandler eh = (ErrorHandler) OptionConverter.instantiateByClassName(
            subst(element.getAttribute(CLASS_ATTR)),
            ErrorHandler.class,
            null);

    if (eh != null) {
        eh.setAppender(appender);

        PropertySetter propSetter = new PropertySetter(eh);
        forEachElement(element.getChildNodes(), (currentElement) -> {
            String tagName = currentElement.getTagName();
            if (tagName.equals(PARAM_TAG)) {
                setParameter(currentElement, propSetter);
            }
        });
        propSetter.activate();
        appender.setErrorHandler(eh);
    }
}
 
Example #16
Source File: MDCLoggingTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
private void setCustomLogger() {
    String PATTERN = "Modified Log *** ProcessDefinitionId=%X{mdcProcessDefinitionID} executionId=%X{mdcExecutionId} mdcProcessInstanceID=%X{mdcProcessInstanceID} mdcBusinessKey=%X{mdcBusinessKey} mdcTaskId=%X{mdcTaskId}  %m%n";
    console.setLayout(new PatternLayout(PATTERN));
    console.setThreshold(Level.DEBUG);
    console.activateOptions();
    console.setName("MemoryAppender");

    appenders = new ArrayList<Appender>();
    Enumeration<?> appendersEnum = Logger.getRootLogger().getAllAppenders();

    while (appendersEnum.hasMoreElements()) {
        Appender object = (Appender) appendersEnum.nextElement();
        appenders.add(object);
    }

    removeAppenders();

    Logger.getRootLogger().addAppender(console);
}
 
Example #17
Source File: TezUtilsInternal.java    From tez with Apache License 2.0 6 votes vote down vote up
public static void updateLoggers(String addend) throws FileNotFoundException {

    LOG.info("Redirecting log file based on addend: " + addend);

    Appender appender = org.apache.log4j.Logger.getRootLogger().getAppender(
        TezConstants.TEZ_CONTAINER_LOGGER_NAME);
    if (appender != null) {
      if (appender instanceof TezContainerLogAppender) {
        TezContainerLogAppender claAppender = (TezContainerLogAppender) appender;
        claAppender.setLogFileName(constructLogFileName(
            TezConstants.TEZ_CONTAINER_LOG_FILE_NAME, addend));
        claAppender.activateOptions();
      } else {
        LOG.warn("Appender is a " + appender.getClass() + "; require an instance of "
            + TezContainerLogAppender.class.getName() + " to reconfigure the logger output");
      }
    } else {
      LOG.warn("Not configured with appender named: " + TezConstants.TEZ_CONTAINER_LOGGER_NAME
          + ". Cannot reconfigure logger output");
    }
  }
 
Example #18
Source File: XmlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Used internally to parse the children of a LoggerConfig element.
 */
private void parseChildrenOfLoggerElement(Element catElement, LoggerConfig loggerConfig, boolean isRoot) {

    final PropertySetter propSetter = new PropertySetter(loggerConfig);
    loggerConfig.getAppenderRefs().clear();
    forEachElement(catElement.getChildNodes(), (currentElement) -> {
        switch (currentElement.getTagName()) {
            case APPENDER_REF_TAG: {
                Appender appender = findAppenderByReference(currentElement);
                String refName = subst(currentElement.getAttribute(REF_ATTR));
                if (appender != null) {
                    LOGGER.debug("Adding appender named [{}] to loggerConfig [{}].", refName,
                            loggerConfig.getName());
                    loggerConfig.addAppender(configuration.getAppender(refName), null, null);
                } else {
                    LOGGER.debug("Appender named [{}}] not found.", refName);
                }
                break;
            }
            case LEVEL_TAG: case PRIORITY_TAG: {
                parseLevel(currentElement, loggerConfig, isRoot);
                break;
            }
            case PARAM_TAG: {
                setParameter(currentElement, propSetter);
                break;
            }
            default: {
                quietParseUnrecognizedElement(loggerConfig, currentElement, props);
            }
        }
    });
    propSetter.activate();
}
 
Example #19
Source File: Log4jAppenderHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Construct a new instance, possibly applying a {@code Layout} to the given appender instance.
 *
 * @param appender    the appender to delegate to
 * @param applyLayout {@code true} to apply an emulated layout, {@code false} otherwise
 */
public Log4jAppenderHandler(final Appender appender, final boolean applyLayout) {
    this.applyLayout = applyLayout;
    if (applyLayout) {
        appender.setLayout(null);
    }
    appenderUpdater.set(this, appender);
}
 
Example #20
Source File: LoggerDynamicMBean.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
void addAppender(String appenderClass, String appenderName) {
  cat.debug("addAppender called with "+appenderClass+", "+appenderName);
  Appender appender = (Appender)
     OptionConverter.instantiateByClassName(appenderClass,
			      org.apache.log4j.Appender.class,
			      null);
  appender.setName(appenderName);
  logger.addAppender(appender);

  //appenderMBeanRegistration();

}
 
Example #21
Source File: AsyncAppenderWithStorage.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * When an appender is added, then the content of the storage is append into
 * the added appender.
 * @see org.apache.log4j.AsyncAppender#addAppender(org.apache.log4j.Appender)
 */
@Override
public synchronized void addAppender(final Appender newAppender) {
    super.addAppender(newAppender);
    // flush the buffer into the sink
    appendStoredEvents(newAppender);
}
 
Example #22
Source File: FilePublisher.java    From kinesis-log4j-appender with Apache License 2.0 5 votes vote down vote up
private static long getBufferedRecordsCountFromKinesisAppenders() {
  long bufferedRecordsCount = 0;
  Enumeration allAppenders = LOGGER.getAllAppenders();
  while (allAppenders.hasMoreElements()) {
    Appender appender = (Appender) allAppenders.nextElement();
    if (appender instanceof KinesisAppender) {
      bufferedRecordsCount += ((KinesisAppender) appender).getTaskBufferSize();
    }
  }
  return bufferedRecordsCount;
}
 
Example #23
Source File: LoggerDynamicMBean.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
void appenderMBeanRegistration() {
  Enumeration enumeration = logger.getAllAppenders();
  while(enumeration.hasMoreElements()) {
    Appender appender = (Appender) enumeration.nextElement();
    registerAppenderMBean(appender);
  }
}
 
Example #24
Source File: AppenderAttachableImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
   Remove the appender passed as parameter form the list of attached
   appenders.  */
public
void removeAppender(Appender appender) {
  if(appender == null || appenderList == null) 
    return;
  appenderList.removeElement(appender);    
}
 
Example #25
Source File: TerminalPreferences.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setLogging(final String level) {
    super.setLogging(level);
    // Send log output to system.log
    Logger root = Logger.getRootLogger();
    final Appender appender = new TerminalAppender();
    appender.setLayout(new PatternLayout("[%t] %-5p %c - %m%n"));
    root.addAppender(appender);
}
 
Example #26
Source File: PropertyPrinter.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void foundProperty(Object obj, String prefix, String name, Object value) {
  // XXX: Properties encode value.toString()
  if (obj instanceof Appender && "name".equals(name)) {
    return;
  }
  if (doCapitalize) {
    name = capitalize(name);
  }
  out.println(prefix + name + "=" + value.toString());
}
 
Example #27
Source File: TestAuditLogs.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Before
 public void setupCluster() throws Exception {
   // must configure prior to instantiating the namesystem because it
   // will reconfigure the logger if async is enabled
   configureAuditLogs();
   conf = new HdfsConfiguration();
   final long precision = 1L;
   conf.setLong(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY, precision);
   conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
   conf.setBoolean(DFSConfigKeys.DFS_WEBHDFS_ENABLED_KEY, true);
   conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_AUDIT_LOG_ASYNC_KEY, useAsyncLog);
   util = new DFSTestUtil.Builder().setName("TestAuditAllowed").
       setNumFiles(20).build();
   cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
   fs = cluster.getFileSystem();
   util.createFiles(fs, fileName);

   // make sure the appender is what it's supposed to be
   Logger logger = ((Log4JLogger) FSNamesystem.auditLog).getLogger();
   @SuppressWarnings("unchecked")
   List<Appender> appenders = Collections.list(logger.getAllAppenders());
   assertEquals(1, appenders.size());
   assertEquals(useAsyncLog, appenders.get(0) instanceof AsyncAppender);
   
   fnames = util.getFileNames(fileName);
   util.waitReplication(fs, fileName, (short)3);
   userGroupInfo = UserGroupInformation.createUserForTesting(username, groups);
}
 
Example #28
Source File: LoggingConfiguratorTest.java    From selenium-grid-extensions with Apache License 2.0 5 votes vote down vote up
@Test
public void configure_shouldInstallConsoleAppender() throws Exception {
    loggingConfigurator.configure(NO_ARGS);

    Appender appender = Logger.getRootLogger().getAppender("Console");
    assertNotNull(appender);
    assertThat(appender, instanceOf(ConsoleAppender.class));
}
 
Example #29
Source File: DependencyServiceImpl.java    From score with Apache License 2.0 5 votes vote down vote up
private String calculateLogFolderPath() {
    Enumeration e = Logger.getRootLogger().getAllAppenders();
    while (e.hasMoreElements()) {
        Appender app = (Appender) e.nextElement();
        if (app instanceof FileAppender) {
            String logFile = ((FileAppender) app).getFile();
            return new File(logFile).getParentFile().getAbsolutePath();
        }
    }
    return new File(System.getProperty(MavenConfig.APP_HOME), MavenConfig.LOGS_FOLDER_NAME).getAbsolutePath();
}
 
Example #30
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;
}