org.apache.logging.log4j.core.config.ConfigurationSource Java Examples

The following examples show how to use org.apache.logging.log4j.core.config.ConfigurationSource. 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: CustomConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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()
            .setPattern(DEFAULT_PATTERN)
            .setConfiguration(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);
}
 
Example #2
Source File: Log4jContextFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: Log4j2CloudConfigLoggingSystem.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private ConfigurationSource getConfigurationSource(URL url) throws IOException, URISyntaxException {
    URLConnection urlConnection = url.openConnection();
    AuthorizationProvider provider = ConfigurationFactory.authorizationProvider(PropertiesUtil.getProperties());
    provider.addAuthorization(urlConnection);
    if (url.getProtocol().equals(HTTPS)) {
        SslConfiguration sslConfiguration = SslConfigurationFactory.getSslConfiguration();
        if (sslConfiguration != null) {
            ((HttpsURLConnection) urlConnection).setSSLSocketFactory(sslConfiguration.getSslSocketFactory());
            if (!sslConfiguration.isVerifyHostName()) {
                ((HttpsURLConnection) urlConnection).setHostnameVerifier(LaxHostnameVerifier.INSTANCE);
            }
        }
    }
    File file = FileUtils.fileFromUri(url.toURI());
    try {
        if (file != null) {
            return new ConfigurationSource(urlConnection.getInputStream(), FileUtils.fileFromUri(url.toURI()));
        } else {
            return new ConfigurationSource(urlConnection.getInputStream(), url, urlConnection.getLastModified());
        }
    } catch (FileNotFoundException ex) {
        LOGGER.info("Unable to locate file {}, ignoring.", url.toString());
        return null;
    }
}
 
Example #4
Source File: AsyncAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private LoggerContext configure(String configLocation) throws Exception {
    File file = new File(configLocation);
    InputStream is = new FileInputStream(file);
    ConfigurationSource source = new ConfigurationSource(is, file);
    LoggerContextFactory factory = org.apache.logging.log4j.LogManager.getFactory();
    LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
    Configuration configuration;
    if (configLocation.endsWith(".xml")) {
        configuration = new XmlConfigurationFactory().getConfiguration(context, source);
    } else {
        configuration = new PropertiesConfigurationFactory().getConfiguration(context, source);
    }
    assertNotNull("No configuration created", configuration);
    Configurator.reconfigure(configuration);
    return context;
}
 
Example #5
Source File: XmlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Configure log4j by reading in a log4j.dtd compliant XML
 * configuration file.
 */
private void doConfigure() throws FactoryConfigurationError {
    ConfigurationSource source = configuration.getConfigurationSource();
    ParseAction action = new ParseAction() {
        public Document parse(final DocumentBuilder parser) throws SAXException, IOException {
            InputSource inputSource = new InputSource(source.getInputStream());
            inputSource.setSystemId("dummy://log4j.dtd");
            return parser.parse(inputSource);
        }

        public String toString() {
            return configuration.getConfigurationSource().getLocation();
        }
    };
    doConfigure(action);
}
 
Example #6
Source File: XmlConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Configure log4j by reading in a log4j.dtd compliant XML
 * configuration file.
 */
@Override
public void doConfigure() throws FactoryConfigurationError {
    ConfigurationSource source = getConfigurationSource();
    ParseAction action = new ParseAction() {
        public Document parse(final DocumentBuilder parser) throws SAXException, IOException {
            InputSource inputSource = new InputSource(source.getInputStream());
            inputSource.setSystemId("dummy://log4j.dtd");
            return parser.parse(inputSource);
        }

        public String toString() {
            return getConfigurationSource().getLocation();
        }
    };
    doConfigure(action);
}
 
Example #7
Source File: LoggerContextAdmin.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #8
Source File: Log4J2LoggerFactory.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static LoggerContext init() {
  try {
    String fileRef = Boolean.getBoolean(ApplicationProperties.CONSULO_MAVEN_CONSOLE_LOG) ? "/log4j2-console.xml" : "/log4j2-default.xml";

    String text = FileUtil.loadTextAndClose(Log4J2LoggerFactory.class.getResourceAsStream(fileRef));
    text = StringUtil.replace(text, SYSTEM_MACRO, StringUtil.replace(ContainerPathManager.get().getSystemPath(), "\\", "\\\\"));
    text = StringUtil.replace(text, APPLICATION_MACRO, StringUtil.replace(ContainerPathManager.get().getHomePath(), "\\", "\\\\"));
    text = StringUtil.replace(text, LOG_DIR_MACRO, StringUtil.replace(ContainerPathManager.get().getLogPath(), "\\", "\\\\"));

    File file = new File(ContainerPathManager.get().getLogPath());
    if (!file.mkdirs() && !file.exists()) {
      System.err.println("Cannot create log directory: " + file);
    }

    ConfigurationSource source = new ConfigurationSource(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)));

    return Configurator.initialize(Log4J2LoggerFactory.class.getClassLoader(), source);
  }
  catch (Exception e) {
    e.printStackTrace();
    StartupUtil.showMessage("Consulo", e);
    return null;
  }
}
 
Example #9
Source File: JsonConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #10
Source File: LoggerContext.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public void reconfigure(Configuration configuration) {
    setConfiguration(configuration);
    ConfigurationSource source = configuration.getConfigurationSource();
    if (source != null) {
        URI uri = source.getURI();
        if (uri != null) {
            configLocation = uri;
        }
    }
}
 
Example #11
Source File: BuiltConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #12
Source File: BuiltConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public BuiltConfiguration(final LoggerContext loggerContext, final ConfigurationSource source, final Component rootComponent) {
    super(loggerContext, source);
    statusConfig = new StatusConfiguration().setVerboseClasses(VERBOSE_CLASSES).setStatus(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;
}
 
Example #13
Source File: CompositeConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Construct the CompositeConfiguration.
 *
 * @param configurations The List of Configurations to merge.
 */
public CompositeConfiguration(final List<? extends AbstractConfiguration> configurations) {
    super(configurations.get(0).getLoggerContext(), ConfigurationSource.COMPOSITE_SOURCE);
    rootNode = configurations.get(0).getRootNode();
    this.configurations = configurations;
    final String mergeStrategyClassName = PropertiesUtil.getProperties().getStringProperty(MERGE_STRATEGY_PROPERTY,
            DefaultMergeStrategy.class.getName());
    try {
        mergeStrategy = Loader.newInstanceOf(mergeStrategyClassName);
    } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException |
            InstantiationException ex) {
        mergeStrategy = new DefaultMergeStrategy();
    }
    for (final AbstractConfiguration config : configurations) {
        mergeStrategy.mergeRootProperties(rootNode, config);
    }
    final StatusConfiguration statusConfig = new StatusConfiguration().setVerboseClasses(VERBOSE_CLASSES)
            .setStatus(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.setStatus(value.toUpperCase());
        } else if ("dest".equalsIgnoreCase(key)) {
            statusConfig.setDestination(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.setVerbosity(value);
        } else if ("packages".equalsIgnoreCase(key)) {
            pluginPackages.addAll(Arrays.asList(value.split(Patterns.COMMA_SEPARATOR)));
        } else if ("name".equalsIgnoreCase(key)) {
            setName(value);
        }
    }
    statusConfig.initialize();
}
 
Example #14
Source File: XmlConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #15
Source File: JsonConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
    if (!isActive) {
        return null;
    }
    return new JsonConfiguration(loggerContext, source);
}
 
Example #16
Source File: YamlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
    if (!isActive) {
        return null;
    }
    return new YamlConfiguration(loggerContext, source);
}
 
Example #17
Source File: YamlConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #18
Source File: LoggerContextAdmin.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example #19
Source File: Log4j1ConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #20
Source File: BasicConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #21
Source File: PropertiesConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #22
Source File: XmlConfigurationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private LoggerContext configure(String configLocation) throws Exception {
    File file = new File(configLocation);
    InputStream is = new FileInputStream(file);
    ConfigurationSource source = new ConfigurationSource(is, file);
    LoggerContextFactory factory = org.apache.logging.log4j.LogManager.getFactory();
    LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
    Configuration configuration = new XmlConfigurationFactory().getConfiguration(context, source);
    assertNotNull("No configuration created", configuration);
    Configurator.reconfigure(configuration);
    return context;
}
 
Example #23
Source File: PropertiesConfigurationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private LoggerContext configure(String configLocation) throws Exception {
    File file = new File(configLocation);
    InputStream is = new FileInputStream(file);
    ConfigurationSource source = new ConfigurationSource(is, file);
    LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
    Configuration configuration = new PropertiesConfigurationFactory().getConfiguration(context, source);
    assertNotNull("No configuration created", configuration);
    Configurator.reconfigure(configuration);
    return context;
}
 
Example #24
Source File: BasicConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #25
Source File: BasicConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #26
Source File: XmlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void doConfigure(URL url, LoggerContext loggerContext) {
    try {
        ConfigurationSource source = new ConfigurationSource(url.openStream(), url);
        configuration = new Log4j1Configuration(loggerContext, source, 0);
        doConfigure();
    } catch (IOException ioe) {
        LOGGER.error("Unable to process configuration due to {}",  ioe.getMessage());
    }
}
 
Example #27
Source File: XmlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void doConfigure(InputStream inputStream, LoggerContext loggerContext) {
    try {
        ConfigurationSource source = new ConfigurationSource(inputStream);
        configuration = new Log4j1Configuration(loggerContext, source, 0);
        doConfigure();
    } catch (IOException ioe) {
        LOGGER.error("Unable to process configuration due to {}",  ioe.getMessage());
    }
}
 
Example #28
Source File: XmlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * A static version of doConfigure(URL).
 */
public static void configure(final URL url) throws FactoryConfigurationError {
    try {
        InputStream is = url.openStream();
        ConfigurationSource source = new ConfigurationSource(is, url);
        XmlConfigurationFactory factory = new XmlConfigurationFactory(source, 0);
        factory.doConfigure();
        org.apache.logging.log4j.core.config.Configurator.reconfigure(factory.getConfiguration());
    } catch (IOException ioe) {
        LOGGER.error("Unable to process configuration {} due to {}", url.toString(), ioe.getMessage());
    }
}
 
Example #29
Source File: XmlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Read the configuration file <code>configFilename</code> if it
 * exists. Moreover, a thread will be created that will periodically
 * check if <code>configFilename</code> has been created or
 * modified. The period is determined by the <code>delay</code>
 * argument. If a change or file creation is detected, then
 * <code>configFilename</code> is read to configure log4j.
 *
 * @param configFilename A log4j configuration file in XML format.
 * @param delay          The delay in milliseconds to wait between each check.
 */
public static void configureAndWatch(final String configFilename, final long delay) {
    try {
        File file = new File(configFilename);
        InputStream is = new FileInputStream(file);
        ConfigurationSource source = new ConfigurationSource(is, file);
        int seconds = (int) TimeUnit.MILLISECONDS.toSeconds(delay);
        XmlConfigurationFactory factory = new XmlConfigurationFactory(source, seconds);
        factory.doConfigure();
        org.apache.logging.log4j.core.config.Configurator.reconfigure(factory.getConfiguration());

    } catch (IOException ioe) {
        LOGGER.error("Unable to process configuration file {} due to {}", configFilename, ioe.getMessage());
    }
}
 
Example #30
Source File: Log4j1ConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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();
}