Java Code Examples for org.apache.logging.log4j.core.util.NetUtils

The following examples show how to use org.apache.logging.log4j.core.util.NetUtils. These examples are extracted from open source projects. 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
private static JsonTemplateLayout createJsonTemplateLayout4GelfLayout() {
    return JsonTemplateLayout
            .newBuilder()
            .setConfiguration(CONFIGURATION)
            .setCharset(CHARSET)
            .setEventTemplateUri("classpath:GelfLayout.json")
            .setRecyclerFactory(ThreadLocalRecyclerFactory.getInstance())
            .setEventTemplateAdditionalFields(EventTemplateAdditionalFields
                    .newBuilder()
                    .setAdditionalFields(
                            new EventTemplateAdditionalField[]{
                                    // Adding "host" as a constant rather than using
                                    // the "hostName" property lookup at runtime, which
                                    // is what GelfLayout does as well.
                                    EventTemplateAdditionalField
                                            .newBuilder()
                                            .setKey("host")
                                            .setValue(NetUtils.getLocalHostname())
                                            .build()
                            })
                    .build())
            .build();
}
 
Example 2
Source Project: logging-log4j2   Source File: StatusConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
private PrintStream parseStreamName(final String name) throws URISyntaxException, FileNotFoundException {
    if (name == null || name.equalsIgnoreCase("out")) {
        return DEFAULT_STREAM;
    }
    if (name.equalsIgnoreCase("err")) {
        return System.err;
    }
    final URI destUri = NetUtils.toURI(name);
    final File output = FileUtils.fileFromUri(destUri);
    if (output == null) {
        // don't want any NPEs, no sir
        return DEFAULT_STREAM;
    }
    final FileOutputStream fos = new FileOutputStream(output);
    return new PrintStream(fos, true);
}
 
Example 3
Source Project: logging-log4j2   Source File: Configurator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the Logging Context.
 * @param name The Context name.
 * @param loader The ClassLoader for the Context (or null).
 * @param configLocation The configuration for the logging context (or null, or blank).
 * @param externalContext The external context to be attached to the LoggerContext
 * @return The LoggerContext or null if an error occurred (check the status logger).
 */
public static LoggerContext initialize(final String name, final ClassLoader loader, final String configLocation,
        final Object externalContext) {
    if (Strings.isBlank(configLocation)) {
        return initialize(name, loader, (URI) null, externalContext);
    }
    if (configLocation.contains(",")) {
        final String[] parts = configLocation.split(",");
        String scheme = null;
        final List<URI> uris = new ArrayList<>(parts.length);
        for (final String part : parts) {
            final URI uri = NetUtils.toURI(scheme != null ? scheme + ":" + part.trim() : part.trim());
            if (scheme == null && uri.getScheme() != null) {
                scheme = uri.getScheme();
            }
            uris.add(uri);
        }
        return initialize(name, loader, uris, externalContext);
    }
    return initialize(name, loader, NetUtils.toURI(configLocation), externalContext);
}
 
Example 4
Source Project: logging-log4j2   Source File: GelfLayout.java    License: Apache License 2.0 6 votes vote down vote up
private GelfLayout(final Configuration config, final String host, final KeyValuePair[] additionalFields,
        final CompressionType compressionType, final int compressionThreshold, final boolean includeStacktrace,
        final boolean includeThreadContext, final boolean includeNullDelimiter, final ListChecker listChecker,
        final PatternLayout patternLayout) {
    super(config, StandardCharsets.UTF_8, null, null);
    this.host = host != null ? host : NetUtils.getLocalHostname();
    this.additionalFields = additionalFields != null ? additionalFields : new KeyValuePair[0];
    if (config == null) {
        for (final KeyValuePair additionalField : this.additionalFields) {
            if (valueNeedsLookup(additionalField.getValue())) {
                throw new IllegalArgumentException("configuration needs to be set when there are additional fields with variables");
            }
        }
    }
    this.compressionType = compressionType;
    this.compressionThreshold = compressionThreshold;
    this.includeStacktrace = includeStacktrace;
    this.includeThreadContext = includeThreadContext;
    this.includeNullDelimiter = includeNullDelimiter;
    if (includeNullDelimiter && compressionType != CompressionType.OFF) {
        throw new IllegalArgumentException("null delimiter cannot be used with compression");
    }
    this.fieldWriter = new FieldWriter(listChecker);
    this.layout = patternLayout;
}
 
Example 5
Source Project: logging-log4j2   Source File: HostNameTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHostname() {
    final org.apache.logging.log4j.Logger testLogger = context.getLogger("org.apache.logging.log4j.hosttest");
    testLogger.debug("Hello, {}", "World");
    final List<String> msgs = host.getMessages();
    assertThat(msgs, hasSize(1));
    String expected = NetUtils.getLocalHostname() + Strings.LINE_SEPARATOR;
    assertThat(msgs.get(0), endsWith(expected));
    assertNotNull("No Host FileAppender file name", hostFile.getFileName());
    expected = "target/" + NetUtils.getLocalHostname() + ".log";
    String name = hostFile.getFileName();
    assertEquals("Incorrect HostFile FileAppender file name - expected " + expected + " actual - " + name, name,
        expected);
    name = hostFile.getFilePattern();
    assertNotNull("No file pattern", name);
    expected = "target/" + NetUtils.getLocalHostname() + "-%d{MM-dd-yyyy}-%i.log";
    assertEquals("Incorrect HostFile FileAppender file pattern - expected " + expected + " actual - " + name, name,
        expected);

}
 
Example 6
Source Project: logging-log4j2   Source File: SmtpManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SmtpManager createManager(final String name, final FactoryData data) {
    final String prefix = "mail." + data.protocol;

    final Properties properties = PropertiesUtil.getSystemProperties();
    properties.setProperty("mail.transport.protocol", data.protocol);
    if (properties.getProperty("mail.host") == null) {
        // Prevent an UnknownHostException in Java 7
        properties.setProperty("mail.host", NetUtils.getLocalHostname());
    }

    if (null != data.host) {
        properties.setProperty(prefix + ".host", data.host);
    }
    if (data.port > 0) {
        properties.setProperty(prefix + ".port", String.valueOf(data.port));
    }

    final Authenticator authenticator = buildAuthenticator(data.username, data.password);
    if (null != authenticator) {
        properties.setProperty(prefix + ".auth", "true");
    }

    if (data.protocol.equals("smtps")) {
        final SslConfiguration sslConfiguration = data.sslConfiguration;
        if (sslConfiguration != null) {
            final SSLSocketFactory sslSocketFactory = sslConfiguration.getSslSocketFactory();
            properties.put(prefix + ".ssl.socketFactory", sslSocketFactory);
            properties.setProperty(prefix + ".ssl.checkserveridentity", Boolean.toString(sslConfiguration.isVerifyHostName()));
        }
    }

    final Session session = Session.getInstance(properties, authenticator);
    session.setProtocolForAddress("rfc822", data.protocol);
    session.setDebug(data.isDebug);
    return new SmtpManager(name, session, null, data);
}
 
Example 7
Source Project: logging-log4j2   Source File: ConfigurationFactory.java    License: Apache License 2.0 5 votes vote down vote up
private Configuration getConfiguration(String requiredVersion, final LoggerContext loggerContext,
        final String configLocationStr) {
    ConfigurationSource source = null;
    try {
        source = ConfigurationSource.fromUri(NetUtils.toURI(configLocationStr));
    } catch (final Exception ex) {
        // Ignore the error and try as a String.
        LOGGER.catching(Level.DEBUG, ex);
    }
    if (source == null) {
        final ClassLoader loader = LoaderUtil.getThreadContextClassLoader();
        source = getInputFromString(configLocationStr, loader);
    }
    if (source != null) {
        for (final ConfigurationFactory factory : getFactories()) {
            if (requiredVersion != null && !factory.getVersion().equals(requiredVersion)) {
                continue;
            }
            final String[] types = factory.getSupportedTypes();
            if (types != null) {
                for (final String type : types) {
                    if (type.equals(ALL_TYPES) || configLocationStr.endsWith(type)) {
                        final Configuration config = factory.getConfiguration(loggerContext, source);
                        if (config != null) {
                            return config;
                        }
                    }
                }
            }
        }
    }
    return null;
}
 
Example 8
Source Project: xyz-hub   Source File: Service.java    License: Apache License 2.0 4 votes vote down vote up
private static void initializeLogger(Config config) {
  if (!CONSOLE_LOG_CONFIG.equals(config.LOG_CONFIG)) {
    Configurator.reconfigure(NetUtils.toURI(config.LOG_CONFIG));
  }
}
 
Example 9
Source Project: logging-log4j2   Source File: Log4jWebInitializerImpl.java    License: Apache License 2.0 4 votes vote down vote up
private Log4jWebInitializerImpl(final ServletContext servletContext) {
    this.servletContext = servletContext;
    this.map.put("hostName", NetUtils.getLocalHostname());
}
 
Example 10
Source Project: logging-log4j2   Source File: Log4jWebInitializerImpl.java    License: Apache License 2.0 4 votes vote down vote up
private URI getConfigURI(final String location) {
    try {
        String configLocation = location;
        if (configLocation == null) {
            final String[] paths = SetUtils.prefixSet(servletContext.getResourcePaths(WEB_INF), WEB_INF + "log4j2");
            LOGGER.debug("getConfigURI found resource paths {} in servletContext at [{}]", Arrays.toString(paths), WEB_INF);
            if (paths.length == 1) {
                configLocation = paths[0];
            } else if (paths.length > 1) {
                final String prefix = WEB_INF + "log4j2-" + this.name + ".";
                boolean found = false;
                for (final String str : paths) {
                    if (str.startsWith(prefix)) {
                        configLocation = str;
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    configLocation = paths[0];
                }
            }
        }
        if (configLocation != null) {
            final URL url = servletContext.getResource(configLocation);
            if (url != null) {
                final URI uri = url.toURI();
                LOGGER.debug("getConfigURI found resource [{}] in servletContext at [{}]", uri, configLocation);
                return uri;
            }
        }
    } catch (final Exception ex) {
        // Just try passing the location.
    }
    if (location != null) {
        try {
            final URI correctedFilePathUri = NetUtils.toURI(location);
            LOGGER.debug("getConfigURI found [{}] in servletContext at [{}]", correctedFilePathUri, location);
            return correctedFilePathUri;
        } catch (final Exception e) {
            LOGGER.error("Unable to convert configuration location [{}] to a URI", location, e);
        }
    }
    return null;
}
 
Example 11
Source Project: logging-log4j2   Source File: ScriptFile.java    License: Apache License 2.0 4 votes vote down vote up
@PluginFactory
public static ScriptFile createScript(
        // @formatter:off
        @PluginAttribute String name,
        @PluginAttribute String language,
        @PluginAttribute("path") final String filePathOrUri,
        @PluginAttribute final Boolean isWatched,
        @PluginAttribute final Charset charset) {
        // @formatter:on
    if (filePathOrUri == null) {
        LOGGER.error("No script path provided for ScriptFile");
        return null;
    }
    if (name == null) {
        name = filePathOrUri;
    }
    final URI uri = NetUtils.toURI(filePathOrUri);
    final File file = FileUtils.fileFromUri(uri);
    if (language == null && file != null) {
        final String fileExtension = FileUtils.getFileExtension(file);
        if (fileExtension != null) {
            final ExtensionLanguageMapping mapping = ExtensionLanguageMapping.getByExtension(fileExtension);
            if (mapping != null) {
                language = mapping.getLanguage();
            }
        }
    }
    if (language == null) {
        LOGGER.info("No script language supplied, defaulting to {}", DEFAULT_LANGUAGE);
        language = DEFAULT_LANGUAGE;
    }

    final Charset actualCharset = charset == null ? Charset.defaultCharset() : charset;
    String scriptText;
    try (final Reader reader = new InputStreamReader(
            file != null ? new FileInputStream(file) : uri.toURL().openStream(), actualCharset)) {
        scriptText = IOUtils.toString(reader);
    } catch (final IOException e) {
        LOGGER.error("{}: language={}, path={}, actualCharset={}", e.getClass().getSimpleName(),
                language, filePathOrUri, actualCharset);
        return null;
    }
    final Path path = file != null ? Paths.get(file.toURI()) : Paths.get(uri);
    if (path == null) {
        LOGGER.error("Unable to convert {} to a Path", uri.toString());
        return null;
    }
    return new ScriptFile(name, path, language, isWatched == null ? Boolean.FALSE : isWatched, scriptText);
}
 
Example 12
Source Project: logging-log4j2   Source File: LoggerContext.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Sets the Configuration to be used.
 *
 * @param config The new Configuration.
 * @return The previous Configuration.
 */
public Configuration setConfiguration(final Configuration config) {
    if (config == null) {
        LOGGER.error("No configuration found for context '{}'.", contextName);
        // No change, return the current configuration.
        return this.configuration;
    }
    configLock.lock();
    try {
        final Configuration prev = this.configuration;
        config.addListener(this);

        final ConcurrentMap<String, String> map = config.getComponent(Configuration.CONTEXT_PROPERTIES);

        try { // LOG4J2-719 network access may throw android.os.NetworkOnMainThreadException
            map.putIfAbsent("hostName", NetUtils.getLocalHostname());
        } catch (final Exception ex) {
            LOGGER.debug("Ignoring {}, setting hostName to 'unknown'", ex.toString());
            map.putIfAbsent("hostName", "unknown");
        }
        map.putIfAbsent("contextName", contextName);
        config.start();
        this.configuration = config;
        updateLoggers();
        if (prev != null) {
            prev.removeListener(this);
            prev.stop();
        }

        firePropertyChangeEvent(new PropertyChangeEvent(this, PROPERTY_CONFIG, prev, config));

        try {
            Server.reregisterMBeansAfterReconfigure();
        } catch (final LinkageError | Exception e) {
            // LOG4J2-716: Android has no java.lang.management
            LOGGER.error("Could not reconfigure JMX", e);
        }
        // AsyncLoggers update their nanoClock when the configuration changes
        Log4jLogEvent.setNanoClock(configuration.getNanoClock());

        return prev;
    } finally {
        configLock.unlock();
    }
}
 
Example 13
private InputStream openInputStream(final String filePathOrUri) {
    return ConfigurationSource.fromUri(NetUtils.toURI(filePathOrUri)).getInputStream();
}