private static void initLog4j() { String log4jConfigFolderPath = System.getProperty("motu-config-dir"); if (log4jConfigFolderPath != null && log4jConfigFolderPath.length() > 0) { if (!log4jConfigFolderPath.endsWith("/")) { log4jConfigFolderPath += "/"; } } else { System.err.println("Error while initializing log4j. Property is not set motu-config-dir or has a bad value"); } // Do not use system property to avoid conflicts with other tomcat webapps // System.setProperty("log4j.configurationFile", log4jConfigFolderPath + "log4j.xml"); try { ConfigurationSource source = new ConfigurationSource(new FileInputStream(log4jConfigFolderPath + "log4j.xml")); Configurator.initialize(null, source); } catch (IOException e) { System.err.println("Error while initializing log4j from file: " + log4jConfigFolderPath + "log4j.xml"); e.printStackTrace(); } }
@Override protected void setUp() throws Exception { super.setUp(); initLogFormatter(); System.getProperties().setProperty(Logging.LOG_CLASS_NAME, "com.devexperts.logging.Log4j2Logging"); // Create log file in folder that will be eventually cleared - "deleteOnExit" does not work for log files. BUILD_TEST_DIR.mkdirs(); logFile = File.createTempFile("test.", ".log", BUILD_TEST_DIR); final Properties props = new Properties(); props.load(Log4jCompatibilityTest.class.getResourceAsStream("/test.log4j2.properties")); props.setProperty("appender.file.fileName", logFile.getPath()); LoggerContext context = (LoggerContext)LogManager.getContext(false); ConfigurationFactory.setConfigurationFactory(new PropertiesConfigurationFactory() { @Override public PropertiesConfiguration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { return new PropertiesConfigurationBuilder() .setConfigurationSource(source) .setRootProperties(props) .setLoggerContext(loggerContext) .build(); } }); context.setConfigLocation(Log4jCompatibilityTest.class.getResource("/test.log4j2.properties").toURI()); }
/** * Constructor to create the default configuration. */ public StandaloneLoggerConfiguration(ConfigurationSource source) { super(source); setName(CONFIG_NAME); final Appender appender = StandaloneLogEventAppender.createAppender("StandaloneLogAppender", 1000); appender.start(); addAppender(appender); final LoggerConfig root = getRootLogger(); root.addAppender(appender, null, null); final String levelName = PropertiesUtil.getProperties().getStringProperty(DEFAULT_LEVEL); final Level level = levelName != null && Level.valueOf(levelName) != null ? Level.valueOf(levelName) : Level.ALL; root.setLevel(level); }
protected void loadConfiguration(String location, LogFile logFile) { Assert.notNull(location, "Location must not be null"); if (logFile != null) { logFile.applyToSystemProperties(); } try { LoggerContext ctx = getLoggerContext(); URL url = ResourceUtils.getURL(location); ConfigurationSource source = getConfigurationSource(url); ctx.start(ConfigurationFactory.getInstance().getConfiguration(source)); } catch (Exception ex) { throw new IllegalStateException( "Could not initialize Log4J2 logging from " + location, ex); } }
/** * Ctor. The configuration is built using instance of * {@link Spec}: * * <ul> * <li>The name is set to {@link Spec#getName()}. * <li>Appenders from the parent object are cleared. * <li>{@link Appender}s are created * {@link #buildAppenders(Spec)}. * <li>{@link LoggerConfig}s are created using * {@link #buildLoggerConfigs(Spec)}. * <li>Every {@link LoggerConfig} is configured with its * {@link Appender} using * {@link #configureLoggerAppenders(Spec, Map, Map)}. * <li>Root loggers are configured. * </ul> * * @param spec */ EmbeddedConfiguration(Spec spec) { super(ConfigurationSource.NULL_SOURCE); setName(spec.getName()); // Clean up first getAppenders().clear(); getRootLogger().getAppenders().clear(); // Build Appenders final Map<String, Appender> appenders = buildAppenders(spec); final Map<String, SyslogAppender> syslogAppenders = buildSyslogAppenders(spec); // Build Logger Configs final Map<String, LoggerConfig> loggers = buildLoggerConfigs(spec); // Configure loggers with appenders configureLoggerAppenders(spec, appenders, loggers); // Configure root logger appenders configureRootLogger(spec, appenders, syslogAppenders); }
/** * Constructor to create the default configuration. */ public CustomConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) { super(loggerContext, source); setName(CONFIG_NAME); final Layout<? extends Serializable> layout = PatternLayout.newBuilder() .withPattern(DEFAULT_PATTERN) .withConfiguration(this) .build(); final Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout); appender.start(); addAppender(appender); final LoggerConfig root = getRootLogger(); root.addAppender(appender, null, null); final String levelName = PropertiesUtil.getProperties().getStringProperty(DEFAULT_LEVEL); final Level level = levelName != null && Level.valueOf(levelName) != null ? Level.valueOf(levelName) : Level.ERROR; root.setLevel(level); }
@Override public void setConfigText(final String configText, final String charsetName) { LOGGER.debug("---------"); LOGGER.debug("Remote request to reconfigure from config text."); try { final InputStream in = new ByteArrayInputStream(configText.getBytes(charsetName)); final ConfigurationSource source = new ConfigurationSource(in); final Configuration updated = ConfigurationFactory.getInstance().getConfiguration(loggerContext, source); loggerContext.start(updated); LOGGER.debug("Completed remote request to reconfigure from config text."); } catch (final Exception ex) { final String msg = "Could not reconfigure from config text"; LOGGER.error(msg, ex); throw new IllegalArgumentException(msg, ex); } }
@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); }
/** * Loads the LoggerContext using the ContextSelector. * @param fqcn The fully qualified class name of the caller. * @param loader The ClassLoader to use or null. * @param externalContext An external context (such as a ServletContext) to be associated with the LoggerContext. * @param currentContext If true returns the current Context, if false returns the Context appropriate * for the caller if a more appropriate Context can be determined. * @param source The configuration source. * @return The LoggerContext. */ public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext, final boolean currentContext, final ConfigurationSource source) { final LoggerContext ctx = selector.getContext(fqcn, loader, currentContext, null); if (externalContext != null && ctx.getExternalContext() == null) { ctx.setExternalContext(externalContext); } if (ctx.getState() == LifeCycle.State.INITIALIZED) { if (source != null) { ContextAnchor.THREAD_CONTEXT.set(ctx); final Configuration config = ConfigurationFactory.getInstance().getConfiguration(ctx, source); LOGGER.debug("Starting LoggerContext[name={}] from configuration {}", ctx.getName(), source); ctx.start(config); ContextAnchor.THREAD_CONTEXT.remove(); } else { ctx.start(); } } return ctx; }
@Test public void testLoggerReconfiguration() throws Exception { setLogLevel(logger, Level.ERROR); Map<String, Long> expectedCounts = getCurrentCounts(); expectedCounts.compute("total", (s, aLong) -> aLong + 1); expectedCounts.compute("error", (s, aLong) -> aLong + 1); Properties properties = new Properties(); properties.setProperty("name", "PropertiesConfig"); properties.setProperty("appenders", "console"); properties.setProperty("appender.console.type", "Console"); properties.setProperty("appender.console.name", "STDOUT"); properties.setProperty("rootLogger.level", "debug"); properties.setProperty("rootLogger.appenderRefs", "stdout"); properties.setProperty("rootLogger.appenderRefs", "stdout"); properties.setProperty("rootLogger.appenderRef.stdout.ref", "STDOUT"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); properties.store(baos, null); ConfigurationSource source = new ConfigurationSource( new ByteArrayInputStream(baos.toByteArray())); PropertiesConfigurationFactory factory = new PropertiesConfigurationFactory(); LoggerContext context = (LoggerContext) LogManager.getContext(false); PropertiesConfiguration configuration = factory.getConfiguration(context, source); configuration.start(); context.updateLoggers(configuration); logger.error("error!"); assertEquals(expectedCounts, getCurrentCounts()); }
public BasicConfiguration() { super(null, ConfigurationSource.NULL_SOURCE); final LoggerConfig root = getRootLogger(); final String name = System.getProperty(DEFAULT_LEVEL); final Level level = (name != null && Level.getLevel(name) != null) ? Level.getLevel(name) : Level.ERROR; root.setLevel(level); }
@Override public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { if (source != null && source != ConfigurationSource.NULL_SOURCE) { if (LoggingSystem.get(loggerContext.getClass().getClassLoader()) != null) { return new DefaultConfiguration(); } } return null; }
protected void loadConfiguration(String location, LogFile logFile) { Assert.notNull(location, "Location must not be null"); try { LoggerContext ctx = getLoggerContext(); URL url = ResourceUtils.getURL(location); ConfigurationSource source = getConfigurationSource(url); ctx.start(ConfigurationFactory.getInstance().getConfiguration(source)); } catch (Exception ex) { throw new IllegalStateException( "Could not initialize Log4J2 logging from " + location, ex); } }
private ConfigurationSource getConfigurationSource(URL url) throws IOException { InputStream stream = url.openStream(); if (FILE_PROTOCOL.equals(url.getProtocol())) { return new ConfigurationSource(stream, ResourceUtils.getFile(url)); } return new ConfigurationSource(stream, url); }
private ConfigurationSource getConfigurationSource(URL url) throws IOException { InputStream stream = url.openStream(); if (ResourceUtils.isFileURL(url)) { return new ConfigurationSource(stream, ResourceUtils.getFile(url)); } return new ConfigurationSource(stream, url); }
public void contextInitialized(ServletContextEvent sce) { ServletContext context = sce.getServletContext( ); String url = context.getInitParameter("logger-config"); WebAppFileLoader fileLoader = new WebAppFileLoader(url, sce.getServletContext( )); try { Configurator.initialize(null, new ConfigurationSource(fileLoader.load())); } catch (Exception e) { System.err.println("Couldn't load the log4j properties file on '"+url+"'"); e.printStackTrace(); } }
public static void main(String[] args) { try { ConfigurationSource cs = new ConfigurationSource(Main.class.getClassLoader().getResourceAsStream("org/logger/config/log4j2.xml")); Configurator.initialize(null, cs); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //LoggerContext.getContext().setConfiguration(cs); //System.setProperty("log4j.configurationFile", MyLogger.class.getClassLoader().getResource("org/logger/config/log4j2.xml").getPath()); MyLogger.setMode(MyLogger.CONSOLE_MODE); MyLogger.setLevel(GlobalConfig.getProperty("loglevel")); OS.getFolderFirmwaresDownloaded(); OS.getFolderFirmwaresPrepared(); OS.getFolderFirmwaresSinExtracted(); OS.getFolderMyDevices(); OS.getFolderRegisteredDevices(); AWTKillerThread k = new AWTKillerThread(); k.start(); try { OptionSet options = parseCmdLine(args); Main.initLinuxUsb(); if (options.has("console")) { processConsole(options); } else { MyLogger.setMode(MyLogger.GUI_MODE); MainSWT window = new MainSWT(); window.open(); } } catch (Exception e) { e.printStackTrace(); } k.done(); }
@Override public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) { final ConfigurationBuilder<BuiltConfiguration> builder; try (final InputStream configStream = source.getInputStream()) { builder = new Log4j1ConfigurationParser().buildConfigurationBuilder(configStream); } catch (final IOException e) { throw new ConfigurationException("Unable to load " + source, e); } return builder.build(); }
public BasicConfiguration(final LoggerContext loggerContext) { super(loggerContext, ConfigurationSource.NULL_SOURCE); final LoggerConfig root = getRootLogger(); setName("BasicConfiguration"); final String levelName = System.getProperty(DEFAULT_LEVEL); final Level level = (levelName != null && Level.getLevel(levelName) != null) ? Level.getLevel(levelName) : Level.DEBUG; root.setLevel(level); }
@Override public String getConfigText(final String charsetName) throws IOException { try { final ConfigurationSource source = loggerContext.getConfiguration().getConfigurationSource(); final ConfigurationSource copy = source.resetInputStream(); final Charset charset = Charset.forName(charsetName); return readContents(copy.getInputStream(), charset); } catch (final Exception ex) { final StringWriter sw = new StringWriter(BUFFER_SIZE); ex.printStackTrace(new PrintWriter(sw)); return sw.toString(); } }
@Override public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) { if (!isActive) { return null; } return new YamlConfiguration(loggerContext, source); }
@Override public Configuration reconfigure() { try { final ConfigurationSource source = getConfigurationSource().resetInputStream(); if (source == null) { return null; } return new YamlConfiguration(getLoggerContext(), source); } catch (final IOException ex) { LOGGER.error("Cannot locate file {}", getConfigurationSource(), ex); } return null; }
@Override public Configuration reconfigure() { try { final ConfigurationSource source = getConfigurationSource().resetInputStream(); if (source == null) { return null; } return new JsonConfiguration(getLoggerContext(), source); } catch (final IOException ex) { LOGGER.error("Cannot locate file {}", getConfigurationSource(), ex); } return null; }
@Override public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) { if (!isActive) { return null; } return new JsonConfiguration(loggerContext, source); }
@Override public Configuration reconfigure() { try { final ConfigurationSource source = getConfigurationSource().resetInputStream(); if (source == null) { return null; } final PropertiesConfigurationFactory factory = new PropertiesConfigurationFactory(); final PropertiesConfiguration config = factory.getConfiguration(getLoggerContext(), source); return config == null || config.getState() != State.INITIALIZING ? null : config; } catch (final IOException ex) { LOGGER.error("Cannot locate file {}: {}", getConfigurationSource(), ex); } return null; }
@Override public PropertiesConfiguration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) { final Properties properties = new Properties(); try (final InputStream configStream = source.getInputStream()) { properties.load(configStream); } catch (final IOException ioe) { throw new ConfigurationException("Unable to load " + source.toString(), ioe); } return new PropertiesConfigurationBuilder() .setConfigurationSource(source) .setRootProperties(properties) .setLoggerContext(loggerContext) .build(); }
@Override public Configuration reconfigure() { try { final ConfigurationSource source = getConfigurationSource().resetInputStream(); if (source == null) { return null; } final XmlConfiguration config = new XmlConfiguration(getLoggerContext(), source); return config.rootElement == null ? null : config; } catch (final IOException ex) { LOGGER.error("Cannot locate file {}", getConfigurationSource(), ex); } return null; }
/** * 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(); }
public BuiltConfiguration(final LoggerContext loggerContext, final ConfigurationSource source, final Component rootComponent) { super(loggerContext, source); statusConfig = new StatusConfiguration().withVerboseClasses(VERBOSE_CLASSES).withStatus(getDefaultStatus()); for (final Component component : rootComponent.getComponents()) { switch (component.getPluginType()) { case "Scripts": { scriptsComponent = component; break; } case "Loggers": { loggersComponent = component; break; } case "Appenders": { appendersComponent = component; break; } case "Filters": { filtersComponent = component; break; } case "Properties": { propertiesComponent = component; break; } case "CustomLevels": { customLevelsComponent = component; break; } } } this.rootComponent = rootComponent; }
public void createAdvertiser(final String advertiserString, final ConfigurationSource configSource) { byte[] buffer = null; try { if (configSource != null) { final InputStream is = configSource.getInputStream(); if (is != null) { buffer = toByteArray(is); } } } catch (final IOException ioe) { LOGGER.warn("Unable to read configuration source " + configSource.toString()); } super.createAdvertiser(advertiserString, configSource, buffer, contentType); }
public void setMonitorInterval(final int intervalSeconds) { if (this instanceof Reconfigurable && intervalSeconds > 0) { final ConfigurationSource configSource = getConfigurationSource(); if (configSource != null) { final File configFile = configSource.getFile(); if (intervalSeconds > 0) { getWatchManager().setIntervalSeconds(intervalSeconds); if (configFile != null) { final FileWatcher watcher = new ConfiguratonFileWatcher((Reconfigurable) this, listeners); getWatchManager().watchFile(configFile, watcher); } } } } }
@Override public String lookup(final LogEvent event, final String key) { if (configuration != null) { final ConfigurationSource configSrc = configuration.getConfigurationSource(); final File file = configSrc.getFile(); if (file != null) { switch (key) { case KEY_CONFIG_LOCATION: return file.getAbsolutePath(); case KEY_CONFIG_PARENT_LOCATION: return file.getParentFile().getAbsolutePath(); default: return null; } } final URL url = configSrc.getURL(); if (url != null) { try { switch (key) { case KEY_CONFIG_LOCATION: return asPath(url.toURI()); case KEY_CONFIG_PARENT_LOCATION: return asPath(getParent(url.toURI())); default: return null; } } catch (final URISyntaxException use) { LOGGER.error(use); return null; } } } return null; }
@Override public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) { return getConfiguration(loggerContext, source.toString(), null); }
@Override public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) { return null; }
@Override public Configuration getConfiguration (final LoggerContext loggerContext, final ConfigurationSource source) { return getConfiguration (loggerContext, source.toString (), null); }
public StandaloneLoggerConfiguration() { this(ConfigurationSource.NULL_SOURCE); }
@Override public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { return buildConfiguration(); }