Java Code Examples for org.apache.logging.log4j.core.config.ConfigurationSource#getInputStream()

The following examples show how to use org.apache.logging.log4j.core.config.ConfigurationSource#getInputStream() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
Source File: LogConfigurator.java    From crate with Apache License 2.0 4 votes vote down vote up
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);

    loadLog4jPlugins();

    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 Set<String> locationsWithDeprecatedPatterns = Collections.synchronizedSet(new HashSet<>());
    final List<AbstractConfiguration> configurations = new ArrayList<>();
    /*
     * Subclass the properties configurator to hack the new pattern in
     * place so users don't have to change log4j2.properties in
     * a minor release. In 7.0 we'll remove this and force users to
     * change log4j2.properties. If they don't customize log4j2.properties
     * then they won't have to do anything anyway.
     *
     * Everything in this subclass that isn't marked as a hack is copied
     * from log4j2's source.
     */
    final PropertiesConfigurationFactory factory = new PropertiesConfigurationFactory() {
        @Override
        public PropertiesConfiguration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
            final Properties properties = new Properties();
            try (InputStream configStream = source.getInputStream()) {
                properties.load(configStream);
            } catch (final IOException ioe) {
                throw new ConfigurationException("Unable to load " + source.toString(), ioe);
            }
            // Hack the new pattern into place
            for (String name : properties.stringPropertyNames()) {
                if (false == name.endsWith(".pattern")) continue;
                // Null is weird here but we can't do anything with it so ignore it
                String value = properties.getProperty(name);
                if (value == null) continue;
                // Tests don't need to be changed
                if (value.contains("%test_thread_info")) continue;
                /*
                 * Patterns without a marker are sufficiently customized
                 * that we don't have an opinion about them.
                 */
                if (false == value.contains("%marker")) continue;
                if (false == value.contains("%node_name")) {
                    locationsWithDeprecatedPatterns.add(source.getLocation());
                    properties.setProperty(name, value.replace("%marker", "[%node_name]%marker "));
                }
            }
            // end hack
            return new PropertiesConfigurationBuilder()
                    .setConfigurationSource(source)
                    .setRootProperties(properties)
                    .setLoggerContext(loggerContext)
                    .build();
        }
    };
    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);

    final String deprecatedLocationsString = String.join("\n  ", locationsWithDeprecatedPatterns);
    if (deprecatedLocationsString.length() > 0) {
        LogManager.getLogger(LogConfigurator.class).warn("Some logging configurations have %marker but don't have %node_name. "
                + "We will automatically add %node_name to the pattern to ease the migration for users who customize "
                + "log4j2.properties but will stop this behavior in 7.0. You should manually replace `%node_name` with "
                + "`[%node_name]%marker ` in these locations:\n  {}", deprecatedLocationsString);
    }
}
 
Example 8
Source File: JsonConfiguration.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public JsonConfiguration(final LoggerContext loggerContext, final ConfigurationSource configSource) {
    super(loggerContext, configSource);
    final File configFile = configSource.getFile();
    byte[] buffer;
    try {
        try (final InputStream configStream = configSource.getInputStream()) {
            buffer = toByteArray(configStream);
        }
        final InputStream is = new ByteArrayInputStream(buffer);
        root = getObjectMapper().readTree(is);
        if (root.size() == 1) {
            for (final JsonNode node : root) {
                root = node;
            }
        }
        processAttributes(rootNode, root);
        final StatusConfiguration statusConfig = new StatusConfiguration().setVerboseClasses(VERBOSE_CLASSES)
                .setStatus(getDefaultStatus());
        int monitorIntervalSeconds = 0;
        for (final Map.Entry<String, String> entry : rootNode.getAttributes().entrySet()) {
            final String key = entry.getKey();
            final String value = getStrSubstitutor().replace(entry.getValue());
            // TODO: this duplicates a lot of the XmlConfiguration constructor
            if ("status".equalsIgnoreCase(key)) {
                statusConfig.setStatus(value);
            } 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(entry.getKey())) {
                statusConfig.setVerbosity(value);
            } else if ("packages".equalsIgnoreCase(key)) {
                pluginPackages.addAll(Arrays.asList(value.split(Patterns.COMMA_SEPARATOR)));
            } else if ("name".equalsIgnoreCase(key)) {
                setName(value);
            } else if ("monitorInterval".equalsIgnoreCase(key)) {
                monitorIntervalSeconds = Integer.parseInt(value);
            } else if ("advertiser".equalsIgnoreCase(key)) {
                createAdvertiser(value, configSource, buffer, "application/json");
            }
        }
        initializeWatchers(this, configSource, monitorIntervalSeconds);
        statusConfig.initialize();
        if (getName() == null) {
            setName(configSource.getLocation());
        }
    } catch (final Exception ex) {
        LOGGER.error("Error parsing " + configSource.getLocation(), ex);
    }
}