org.apache.log4j.Appender源码实例Demo

org.apache.log4j.AppenderSkeleton#org.apache.log4j.Appender源码实例Demo

下面列出了org.apache.log4j.AppenderSkeleton#org.apache.log4j.Appender 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: logging-log4j2   文件: XmlConfigurationFactory.java
/**
 * 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);
    }
}
 
源代码2 项目: dubbox   文件: Log4jLoggerAdapter.java
@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) {
       }
}
 
源代码3 项目: render   文件: LogUtilities.java
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);
}
 
源代码4 项目: logging-log4j2   文件: XmlConfiguration.java
/**
 * 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);
    }
}
 
源代码5 项目: tez   文件: TezUtilsInternal.java
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");
    }
  }
 
源代码6 项目: zeppelin   文件: HeliumBundleFactory.java
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
  ));
}
 
源代码7 项目: tasmo   文件: ModePathPrefixMerging.java
@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);
//        }
    }
 
源代码8 项目: attic-apex-core   文件: LoggerUtil.java
/**
 * 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;
}
 
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;
}
 
源代码10 项目: qiniu-logging-plugin   文件: Clear.java
@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);
}
 
源代码11 项目: ats-framework   文件: LocalSystemOperations.java
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);
                    }
                }
            }
        }
    }
 
源代码12 项目: attic-apex-core   文件: StdOutErrLog.java
@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));
}
 
源代码13 项目: logging-log4j2   文件: RewriteAppenderBuilder.java
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));
}
 
源代码14 项目: dubbox   文件: Log4jLoggerAdapter.java
@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) {
       }
}
 
源代码15 项目: dubbox-hystrix   文件: LogPageHandler.java
@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) {
    }
   }
 
源代码16 项目: flowable-engine   文件: MDCLoggingTest.java
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);
}
 
源代码17 项目: logging-log4j2   文件: AsyncAppenderBuilder.java
@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);
}
 
源代码18 项目: olat   文件: ThreadLocalAwareLogger.java
@Override
public void l7dlog(Priority priority, String key, Throwable t) {
    if (isForcedToLog(priority)) {
        // from super.l7dlog:

        String msg = getResourceBundleString(key);
        // if message corresponding to 'key' could not be found in the
        // resource bundle, then default to 'key'.
        if (msg == null) {
            msg = key;
        }

        final Appender forcedAppender = getForcedAppender();

        // force the logging and modify the log message (the latter might return the original message)
        if (forcedAppender != null) {
            // only call the forced appender
            forcedAppender.doAppend(new LoggingEvent(FQCN, this, priority, modifyLogMessage(msg), t));
        } else {
            // go via the normal appenders
            forcedLog(FQCN, priority, modifyLogMessage(msg), t);
        }

    } else {
        super.l7dlog(priority, key, t);
    }
}
 
public void unload() {
   Logger.getRootLogger().removeAllAppenders();

   while(this.oldAppenders.hasMoreElements()) {
      Appender appender = (Appender)this.oldAppenders.nextElement();
      Logger.getRootLogger().addAppender(appender);
   }

   System.setProperty(this.getClass().getName(), FALSE);
}
 
public void unload() {
   Logger.getRootLogger().removeAllAppenders();

   while(this.oldAppenders.hasMoreElements()) {
      Appender appender = (Appender)this.oldAppenders.nextElement();
      Logger.getRootLogger().addAppender(appender);
   }

   System.setProperty(this.getClass().getName(), FALSE);
}
 
@Test
public void configure_shouldInstallFileAppenderFromArguments() throws Exception {

    String[] arguments = loggingConfigurator.configure(new String[]{"-log", "target/" + LOG_FILENAME});
    assertEquals(0, arguments.length);
    Appender appender = Logger.getRootLogger().getAppender("FileAppender");
    assertNotNull(appender);
    assertThat(appender, instanceOf(RollingFileAppender.class));
    assertThat(((RollingFileAppender) appender).getFile(), endsWith(LOG_FILENAME));
    assertThat(arguments.length, is(0));
}
 
源代码22 项目: seldon-server   文件: FailFast.java
public void run() {
	logger.info("Starting...");
	while (keepChecking) {
		try {
			if (!parentThread.isAlive()) {
				String msg = Thread.currentThread().getName() + ": Killing Process";
				System.out.println(msg);

				{ // Flush the file log appenders
					Enumeration<?> appenders = logger.getAllAppenders();
					while (appenders.hasMoreElements()) {
						Appender  appender = (Appender)appenders.nextElement();
						if (appender instanceof FileAppender) {
							FileAppender fileAppender = (FileAppender)appender;
							fileAppender.setImmediateFlush(true);
						}
					}
				}
				logger.error(msg);
				System.exit(1);
			}
			Thread.sleep(10000); // check every 10 secs
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
 
@Override
public Appender parseAppender(final String name, final String appenderPrefix, final String layoutPrefix,
        final String filterPrefix, final Properties props, final PropertiesConfiguration configuration) {
    Layout layout = configuration.parseLayout(layoutPrefix, name, props);
    Filter filter = configuration.parseAppenderFilters(props, filterPrefix, name);
    String fileName = getProperty(FILE_PARAM);
    String level = getProperty(THRESHOLD_PARAM);
    boolean append = getBooleanProperty(APPEND_PARAM);
    boolean immediateFlush = false;
    boolean bufferedIo = getBooleanProperty(BUFFERED_IO_PARAM);
    int bufferSize = Integer.parseInt(getProperty(BUFFER_SIZE_PARAM, "8192"));
    return createAppender(name, layout, filter, fileName, append, immediateFlush,
            level, bufferedIo, bufferSize, configuration);
}
 
源代码24 项目: logging-log4j2   文件: BuilderManager.java
public Appender parseAppender(String className, Element appenderElement, XmlConfigurationFactory factory) {
    PluginType<?> plugin = plugins.get(className.toLowerCase());
    if (plugin != null) {
        try {
            @SuppressWarnings("unchecked")
            AppenderBuilder builder = (AppenderBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
            return builder.parseAppender(appenderElement, factory);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
            LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
        }
    }
    return null;
}
 
public void close() {
   AppenderAttachableImpl var1 = this.downstreamAppenders;
   synchronized(this.downstreamAppenders) {
      this.flush();
      Enumeration enumer = this.downstreamAppenders.getAllAppenders();

      while(enumer != null && enumer.hasMoreElements()) {
         Appender appender = (Appender)enumer.nextElement();
         appender.close();
      }

   }
}
 
源代码26 项目: cacheonix-core   文件: AppenderAttachableImpl.java
/**
   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);    
}
 
源代码27 项目: logging-log4j2   文件: XmlConfigurationFactory.java
/**
 * 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();
}
 
源代码28 项目: wildfly-core   文件: Log4jAppenderHandler.java
/**
 * 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);
}
 
源代码29 项目: cacheonix-core   文件: LoggerDynamicMBean.java
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();

}
 
源代码30 项目: scheduling   文件: AsyncAppenderWithStorage.java
/**
 * 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);
}