类org.apache.logging.log4j.core.util.NetUtils源码实例Demo

下面列出了怎么用org.apache.logging.log4j.core.util.NetUtils的API类实例代码及写法,或者点击链接到github查看源代码。

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();
}
 
源代码2 项目: logging-log4j2   文件: StatusConfiguration.java
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);
}
 
源代码3 项目: logging-log4j2   文件: Configurator.java
/**
 * 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);
}
 
源代码4 项目: logging-log4j2   文件: GelfLayout.java
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;
}
 
源代码5 项目: logging-log4j2   文件: HostNameTest.java
@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);

}
 
源代码6 项目: logging-log4j2   文件: SmtpManager.java
@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);
}
 
源代码7 项目: logging-log4j2   文件: ConfigurationFactory.java
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;
}
 
源代码8 项目: xyz-hub   文件: Service.java
private static void initializeLogger(Config config) {
  if (!CONSOLE_LOG_CONFIG.equals(config.LOG_CONFIG)) {
    Configurator.reconfigure(NetUtils.toURI(config.LOG_CONFIG));
  }
}
 
源代码9 项目: logging-log4j2   文件: Log4jWebInitializerImpl.java
private Log4jWebInitializerImpl(final ServletContext servletContext) {
    this.servletContext = servletContext;
    this.map.put("hostName", NetUtils.getLocalHostname());
}
 
源代码10 项目: logging-log4j2   文件: Log4jWebInitializerImpl.java
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;
}
 
源代码11 项目: logging-log4j2   文件: ScriptFile.java
@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);
}
 
源代码12 项目: logging-log4j2   文件: LoggerContext.java
/**
 * 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();
    }
}
 
private InputStream openInputStream(final String filePathOrUri) {
    return ConfigurationSource.fromUri(NetUtils.toURI(filePathOrUri)).getInputStream();
}
 
 类所在包
 类方法
 同包方法