public static void main(String[] args) throws UnRetriableException{ LoggerContext ctx = (LoggerContext) LogManager.getContext(false); AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration(); ConsoleAppender appender = ConsoleAppender.createDefaultAppenderForLayout(PatternLayout.createDefaultLayout()); appender.start(); config.addAppender(appender); AppenderRef[] refs = new AppenderRef[] { AppenderRef.createAppenderRef(appender.getName(), null, null) }; LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, LogManager.ROOT_LOGGER_NAME, "true", refs, null, config, null); loggerConfig.addAppender(appender, null, null); config.addLogger(LogManager.ROOT_LOGGER_NAME, loggerConfig); ctx.updateLoggers(); Runner runner = defaultRunner(); runner.init(); runner.start(); }
public static void main(String[] args) throws UnRetriableException { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration(); ConsoleAppender appender = ConsoleAppender.createDefaultAppenderForLayout(PatternLayout.createDefaultLayout()); appender.start(); config.addAppender(appender); AppenderRef[] refs = new AppenderRef[] { AppenderRef.createAppenderRef(appender.getName(), null, null) }; LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.WARN, LogManager.ROOT_LOGGER_NAME, "true", refs, null, config, null); loggerConfig.addAppender(appender, null, null); config.addLogger(LogManager.ROOT_LOGGER_NAME, loggerConfig); ctx.updateLoggers(); Runner runner = defaultRunner(); runner.init(); runner.start(); }
@Before public void setUpAppender() throws IOException { file = folder.newFile(); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); final LoggerConfig root = ((AbstractConfiguration) config).getRootLogger(); PatternLayout layout = PatternLayout.createLayout("[%p] %m%n", config, null, null, true, false, null, null); FileAppender appender = FileAppender.createAppender(file.getAbsolutePath(), "true", "false", "TestLogFile", "true", "false", "false", "8192", layout, null, "false", null, config); appender.start(); config.addAppender(appender); root.addAppender(appender, null, null); ctx.updateLoggers(); }
@Override public Configuration reconfigure() { LOGGER.debug("Reconfiguring composite configuration"); final List<AbstractConfiguration> configs = new ArrayList<>(); final ConfigurationFactory factory = ConfigurationFactory.getInstance(); for (final AbstractConfiguration config : configurations) { final ConfigurationSource source = config.getConfigurationSource(); final URI sourceURI = source.getURI(); Configuration currentConfig = config; if (sourceURI == null) { LOGGER.warn("Unable to determine URI for configuration {}, changes to it will be ignored", config.getName()); } else { currentConfig = factory.getConfiguration(getLoggerContext(), config.getName(), sourceURI); if (currentConfig == null) { LOGGER.warn("Unable to reload configuration {}, changes to it will be ignored", config.getName()); } } configs.add((AbstractConfiguration) currentConfig); } return new CompositeConfiguration(configs); }
private static void configure(final Settings settings, final Path configsPath, final Path logsPath) throws IOException, UserException { Objects.requireNonNull(settings); Objects.requireNonNull(configsPath); Objects.requireNonNull(logsPath); setLogConfigurationSystemProperty(logsPath, settings); // we initialize the status logger immediately otherwise Log4j will complain when we try to get the context configureStatusLogger(); final LoggerContext context = (LoggerContext) LogManager.getContext(false); final List<AbstractConfiguration> configurations = new ArrayList<>(); final PropertiesConfigurationFactory factory = new PropertiesConfigurationFactory(); final Set<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS); Files.walkFileTree(configsPath, options, Integer.MAX_VALUE, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().equals("log4j2.properties")) { configurations.add((PropertiesConfiguration) factory.getConfiguration(context, file.toString(), file.toUri())); } return FileVisitResult.CONTINUE; } }); if (configurations.isEmpty()) { throw new UserException( ExitCodes.CONFIG, "no log4j2.properties found; tried [" + configsPath + "] and its subdirectories"); } context.start(new CompositeConfiguration(configurations)); configureLoggerLevels(settings); }
protected boolean processCommands() throws IOException { final LoggerContext logCtx = (LoggerContext) LogManager.getContext(false); final AbstractConfiguration logConf = (AbstractConfiguration) logCtx.getConfiguration(); LinkedList<String> failedQueue = new LinkedList<>(); logGrabber.grabCurrentThread(); logGrabber.setLogEventList(logs); // start grabbing logs of this thread logConf.getRootLogger().addAppender(logGrabber, logConf.getRootLogger().getLevel(), null); // register session to MCRSessionMgr MCRSessionMgr.setCurrentSession(session); try { while (!commands.isEmpty()) { String command = commands.remove(0); if (!processCommand(command)) { if (!continueIfOneFails) { return false; } failedQueue.add(command); } } if (failedQueue.isEmpty()) { setCurrentCommand(""); return true; } else { saveQueue(null, failedQueue); return false; } } finally { // stop grabbing logs of this thread logConf.removeAppender(logGrabber.getName()); // release session MCRSessionMgr.releaseCurrentSession(); } }
@Override public AbstractConfiguration build() { final Spec spec = new Spec(name, directory, level, asyncLoggers, loggers, appenders, syslogAppenders, appenderFileNamePatterns, appenderHeaders, appenderFooters, appenderPatterns, rootAppenders); return new EmbeddedConfiguration(spec); }
void register() { if (LogManager.getContext(false) instanceof LoggerContext) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); if (ctx.getConfiguration() instanceof AbstractConfiguration) { final AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration(); final Appender appender = getSingleton(); appender.start(); config.addAppender(appender); final Logger rootLogger = LogManager.getRootLogger(); final LoggerConfig loggerConfig = config.getLoggerConfig(rootLogger.getName()); loggerConfig.addAppender(appender, null, null); ctx.updateLoggers(); } } }
void deregister() { if (LogManager.getContext(false) instanceof LoggerContext) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); if (ctx.getConfiguration() instanceof AbstractConfiguration) { final AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration(); final Appender appender = getSingleton(); appender.stop(); config.removeAppender(appender.getName()); final Logger rootLogger = LogManager.getRootLogger(); final LoggerConfig loggerConfig = config.getLoggerConfig(rootLogger.getName()); loggerConfig.removeAppender(appender.getName()); ctx.updateLoggers(); } } }
public static void configureConsoleAppender() { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration(); ConsoleAppender appender = ConsoleAppender.createDefaultAppenderForLayout(PatternLayout.createDefaultLayout()); appender.start(); config.addAppender(appender); AppenderRef[] refs = new AppenderRef[] { AppenderRef.createAppenderRef(appender.getName(), null, null) }; LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.ALL, LogManager.ROOT_LOGGER_NAME, "true", refs, null, config, null); loggerConfig.addAppender(appender, null, null); config.addLogger(LogManager.ROOT_LOGGER_NAME, loggerConfig); ctx.updateLoggers(); }
/** * Construct the ComponsiteConfiguration. * * @param configurations The List of Configurations to merge. */ public CompositeConfiguration(final List<? extends AbstractConfiguration> configurations) { super(configurations.get(0).getLoggerContext(), ConfigurationSource.NULL_SOURCE); rootNode = configurations.get(0).getRootNode(); this.configurations = configurations; final String mergeStrategyClassName = PropertiesUtil.getProperties().getStringProperty(MERGE_STRATEGY_PROPERTY, DefaultMergeStrategy.class.getName()); try { mergeStrategy = LoaderUtil.newInstanceOf(mergeStrategyClassName); } catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException | InvocationTargetException | InstantiationException ex) { mergeStrategy = new DefaultMergeStrategy(); } for (final AbstractConfiguration config : configurations) { mergeStrategy.mergeRootProperties(rootNode, config); } final StatusConfiguration statusConfig = new StatusConfiguration().withVerboseClasses(VERBOSE_CLASSES) .withStatus(getDefaultStatus()); for (final Map.Entry<String, String> entry : rootNode.getAttributes().entrySet()) { final String key = entry.getKey(); final String value = getStrSubstitutor().replace(entry.getValue()); if ("status".equalsIgnoreCase(key)) { statusConfig.withStatus(value.toUpperCase()); } else if ("dest".equalsIgnoreCase(key)) { statusConfig.withDestination(value); } else if ("shutdownHook".equalsIgnoreCase(key)) { isShutdownHookEnabled = !"disable".equalsIgnoreCase(value); } else if ("shutdownTimeout".equalsIgnoreCase(key)) { shutdownTimeoutMillis = Long.parseLong(value); } else if ("verbose".equalsIgnoreCase(key)) { statusConfig.withVerbosity(value); } else if ("packages".equalsIgnoreCase(key)) { pluginPackages.addAll(Arrays.asList(value.split(Patterns.COMMA_SEPARATOR))); } else if ("name".equalsIgnoreCase(key)) { setName(value); } } statusConfig.initialize(); }
/** * Merge the root properties. * @param rootNode The composite root node. * @param configuration The configuration to merge. */ @Override public void mergeRootProperties(final Node rootNode, final AbstractConfiguration configuration) { for (final Map.Entry<String, String> attribute : configuration.getRootNode().getAttributes().entrySet()) { boolean isFound = false; for (final Map.Entry<String, String> targetAttribute : rootNode.getAttributes().entrySet()) { if (targetAttribute.getKey().equalsIgnoreCase(attribute.getKey())) { if (attribute.getKey().equalsIgnoreCase(STATUS)) { final Level targetLevel = Level.getLevel(targetAttribute.getValue().toUpperCase()); final Level sourceLevel = Level.getLevel(attribute.getValue().toUpperCase()); if (targetLevel != null && sourceLevel != null) { if (sourceLevel.isLessSpecificThan(targetLevel)) { targetAttribute.setValue(attribute.getValue()); } } else if (sourceLevel != null) { targetAttribute.setValue(attribute.getValue()); } } else { if (attribute.getKey().equalsIgnoreCase("monitorInterval")) { final int sourceInterval = Integer.parseInt(attribute.getValue()); final int targetInterval = Integer.parseInt(targetAttribute.getValue()); if (targetInterval == 0 || sourceInterval < targetInterval) { targetAttribute.setValue(attribute.getValue()); } } else { targetAttribute.setValue(attribute.getValue()); } } isFound = true; } } if (!isFound) { rootNode.getAttributes().put(attribute.getKey(), attribute.getValue()); } } }
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext, final boolean currentContext, final List<URI> configLocations, final String name) { final LoggerContext ctx = selector .getContext(fqcn, loader, currentContext, null/*this probably needs to change*/); if (externalContext != null && ctx.getExternalContext() == null) { ctx.setExternalContext(externalContext); } if (name != null) { ctx.setName(name); } if (ctx.getState() == LifeCycle.State.INITIALIZED) { if ((configLocations != null && !configLocations.isEmpty())) { ContextAnchor.THREAD_CONTEXT.set(ctx); final List<AbstractConfiguration> configurations = new ArrayList<>(configLocations.size()); for (final URI configLocation : configLocations) { final Configuration currentReadConfiguration = ConfigurationFactory.getInstance() .getConfiguration(ctx, name, configLocation); if (currentReadConfiguration instanceof AbstractConfiguration) { configurations.add((AbstractConfiguration) currentReadConfiguration); } else { LOGGER.error( "Found configuration {}, which is not an AbstractConfiguration and can't be handled by CompositeConfiguration", configLocation); } } final CompositeConfiguration compositeConfiguration = new CompositeConfiguration(configurations); LOGGER.debug("Starting LoggerContext[name={}] from configurations at {}", ctx.getName(), configLocations); ctx.start(compositeConfiguration); ContextAnchor.THREAD_CONTEXT.remove(); } else { ctx.start(); } } return ctx; }
public void deleteAppender(String name){ ((AbstractConfiguration)config).removeAppender(name); }
private void staffChildConfiguration(final AbstractConfiguration childConfiguration) { childConfiguration.setPluginManager(pluginManager); childConfiguration.setScriptManager(scriptManager); childConfiguration.setup(); }
/** * Builds the configuration with {@link #build()} and then * reconfigures the Apache Log4j2 context. The process also * installs a shut-down hook to stop the context: * * <ul> * <li>Builds the configuration into an instance of * {@link EmbeddedConfiguration} using {@link #build()}. * <li>Sets the default {@link ConfigurationFactory} to * {@link EmbeddedConfigurationFactory} using * {@link ConfigurationFactory#setConfigurationFactory(ConfigurationFactory)} * . * <li>If asynchronous loggers are enabled, creates an * instance of {@link AsyncLogger}. If not, creates an * instance of {@link LoggerContext}. * <li>Reconfigures the context using * {@link LoggerContext#reconfigure()}. * <li>Starts the context using * {@link LoggerContext#start()}. * <li>Installs a shut down hook to * {@link Runtime#addShutdownHook(Thread)} to ensure the * logger context is stopped with * {@link LoggerContext#stop()}. * </ul> * * <p> * After running this method, the user is able to use Apache * Log4j as if it was configured using an instance of * {@code log4j.xml}. * * @see ConfigurationFactory * @see LoggerContext#reconfigure() * @see EmbeddedConfigurationFactory * @see EmbeddedConfiguration */ public final void configure() { final LoggerContext context = asyncLoggers ? (AsyncLoggerContext) LogManager.getContext(ConfigurationBuilder.class.getClassLoader(), false) : (LoggerContext) LogManager.getContext(ConfigurationBuilder.class.getClassLoader(), false); final AbstractConfiguration configuration = build(); final EmbeddedConfigurationFactory factory = new EmbeddedConfigurationFactory(configuration); ConfigurationFactory.setConfigurationFactory(factory); context.reconfigure(); context.start(); configuration.start(); final String rootLoggerName = LogManager.ROOT_LOGGER_NAME; final Logger logger = LogManager.getLogger(rootLoggerName); logger.info("Initialized logging configuration: {} (async-loggers={})", configuration.getName(), logger instanceof AsyncLogger); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { logger.info("Stopping logging configuration: {}", configuration.getName()); try { configuration.stop(); context.stop(); } catch (Exception e) { System.err.println(e); } } }, rootLoggerName)); }
/** * Ctor. * * @param configuration */ public EmbeddedConfigurationFactory(AbstractConfiguration configuration) { this.configuration = configuration; }
/** * Merge the root node properties into the configuration. * @param rootNode The composite root node. * @param configuration The configuration to merge. */ void mergeRootProperties(Node rootNode, AbstractConfiguration configuration);