org.apache.logging.log4j.util.PropertiesUtil Java Examples

The following examples show how to use org.apache.logging.log4j.util.PropertiesUtil. 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: PropertiesConfigurationBuilder.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private AppenderComponentBuilder createAppender(final String key, final Properties properties) {
    final String name = (String) properties.remove(CONFIG_NAME);
    if (Strings.isEmpty(name)) {
        throw new ConfigurationException("No name attribute provided for Appender " + key);
    }
    final String type = (String) properties.remove(CONFIG_TYPE);
    if (Strings.isEmpty(type)) {
        throw new ConfigurationException("No type attribute provided for Appender " + key);
    }
    final AppenderComponentBuilder appenderBuilder = builder.newAppender(name, type);
    addFiltersToComponent(appenderBuilder, properties);
    final Properties layoutProps = PropertiesUtil.extractSubset(properties, "layout");
    if (layoutProps.size() > 0) {
        appenderBuilder.add(createLayout(name, layoutProps));
    }

    return processRemainingProperties(appenderBuilder, properties);
}
 
Example #2
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 #3
Source File: DisruptorUtil.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
static int calculateRingBufferSize(final String propertyName) {
    int ringBufferSize = Constants.ENABLE_THREADLOCALS ? RINGBUFFER_NO_GC_DEFAULT_SIZE : RINGBUFFER_DEFAULT_SIZE;
    final String userPreferredRBSize = PropertiesUtil.getProperties().getStringProperty(propertyName,
            String.valueOf(ringBufferSize));
    try {
        int size = Integer.parseInt(userPreferredRBSize);
        if (size < RINGBUFFER_MIN_SIZE) {
            size = RINGBUFFER_MIN_SIZE;
            LOGGER.warn("Invalid RingBufferSize {}, using minimum size {}.", userPreferredRBSize,
                    RINGBUFFER_MIN_SIZE);
        }
        ringBufferSize = size;
    } catch (final Exception ex) {
        LOGGER.warn("Invalid RingBufferSize {}, using default size {}.", userPreferredRBSize, ringBufferSize);
    }
    return Integers.ceilingNextPowerOfTwo(ringBufferSize);
}
 
Example #4
Source File: DisruptorUtil.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
static WaitStrategy createWaitStrategy(final String propertyName, final long timeoutMillis) {
    final String strategy = PropertiesUtil.getProperties().getStringProperty(propertyName, "TIMEOUT");
    LOGGER.trace("property {}={}", propertyName, strategy);
    final String strategyUp = strategy.toUpperCase(Locale.ROOT); // TODO Refactor into Strings.toRootUpperCase(String)
    switch (strategyUp) { // TODO Define a DisruptorWaitStrategy enum?
    case "SLEEP":
        return new SleepingWaitStrategy();
    case "YIELD":
        return new YieldingWaitStrategy();
    case "BLOCK":
        return new BlockingWaitStrategy();
    case "BUSYSPIN":
        return new BusySpinWaitStrategy();
    case "TIMEOUT":
        return new TimeoutBlockingWaitStrategy(timeoutMillis, TimeUnit.MILLISECONDS);
    default:
        return new TimeoutBlockingWaitStrategy(timeoutMillis, TimeUnit.MILLISECONDS);
    }
}
 
Example #5
Source File: LoggerContext.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public void start() {
    LOGGER.debug("Starting LoggerContext[name={}, {}]...", getName(), this);
    if (PropertiesUtil.getProperties().getBooleanProperty("log4j.LoggerContext.stacktrace.on.start", false)) {
        LOGGER.debug("Stack trace to locate invoker",
                new Exception("Not a real error, showing stack trace to locate invoker"));
    }
    if (configLock.tryLock()) {
        try {
            if (this.isInitialized() || this.isStopped()) {
                this.setStarting();
                reconfigure();
                if (this.configuration.isShutdownHookEnabled()) {
                    setUpShutdownHook();
                }
                this.setStarted();
            }
        } finally {
            configLock.unlock();
        }
    }
    LOGGER.debug("LoggerContext[name={}, {}] started OK.", getName(), this);
}
 
Example #6
Source File: BasicAuthorizationProvider.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public BasicAuthorizationProvider(PropertiesUtil props) {
    String userName = props.getStringProperty(PREFIXES,AUTH_USER_NAME,
            () -> props.getStringProperty(CONFIG_USER_NAME));
    String password = props.getStringProperty(PREFIXES, AUTH_PASSWORD,
            () -> props.getStringProperty(CONFIG_PASSWORD));
    String decryptor = props.getStringProperty(PREFIXES, AUTH_PASSWORD_DECRYPTOR,
            () -> props.getStringProperty(PASSWORD_DECRYPTOR));
    if (decryptor != null) {
        try {
            Object obj = LoaderUtil.newInstanceOf(decryptor);
            if (obj instanceof PasswordDecryptor) {
                password = ((PasswordDecryptor) obj).decryptPassword(password);
            }
        } catch (Exception ex) {
            LOGGER.warn("Unable to decrypt password.", ex);
        }
    }
    if (userName != null && password != null) {
        authString = "Basic " + encoder.encodeToString((userName + ":" + password).getBytes());
    }
}
 
Example #7
Source File: ConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public static AuthorizationProvider authorizationProvider(PropertiesUtil props) {
    final String authClass = props.getStringProperty(AUTHORIZATION_PROVIDER);
    AuthorizationProvider provider = null;
    if (authClass != null) {
        try {
            Object obj = LoaderUtil.newInstanceOf(authClass);
            if (obj instanceof AuthorizationProvider) {
                provider = (AuthorizationProvider) obj;
            } else {
                LOGGER.warn("{} is not an AuthorizationProvider, using default", obj.getClass().getName());
            }
        } catch (Exception ex) {
            LOGGER.warn("Unable to create {}, using default: {}", authClass, ex.getMessage());
        }
    }
    if (provider == null) {
        provider = new BasicAuthorizationProvider(props);
    }
    return provider;
}
 
Example #8
Source File: ReliabilityStrategyFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new {@code ReliabilityStrategy} instance based on the value of system property
 * {@code log4j.ReliabilityStrategy}. If not value was specified this method returns a new
 * {@code AwaitUnconditionallyReliabilityStrategy}.
 * <p>
 * Valid values for this system property are {@code "AwaitUnconditionally"} (use
 * {@code AwaitUnconditionallyReliabilityStrategy}), {@code "Locking"} (use {@code LockingReliabilityStrategy}) and
 * {@code "AwaitCompletion"} (use the default {@code AwaitCompletionReliabilityStrategy}).
 * <p>
 * Users may also use this system property to specify the fully qualified class name of a class that implements the
 * {@code ReliabilityStrategy} and has a constructor that accepts a single {@code LoggerConfig} argument.
 * 
 * @param loggerConfig the LoggerConfig the resulting {@code ReliabilityStrategy} is associated with
 * @return a ReliabilityStrategy that helps the specified LoggerConfig to log events reliably during or after a
 *         configuration change
 */
public static ReliabilityStrategy getReliabilityStrategy(final LoggerConfig loggerConfig) {

    final String strategy = PropertiesUtil.getProperties().getStringProperty("log4j.ReliabilityStrategy",
            "AwaitCompletion");
    if ("AwaitCompletion".equals(strategy)) {
        return new AwaitCompletionReliabilityStrategy(loggerConfig);
    }
    if ("AwaitUnconditionally".equals(strategy)) {
        return new AwaitUnconditionallyReliabilityStrategy(loggerConfig);
    }
    if ("Locking".equals(strategy)) {
        return new LockingReliabilityStrategy(loggerConfig);
    }
    try {
        final Class<? extends ReliabilityStrategy> cls = Loader.loadClass(strategy).asSubclass(
            ReliabilityStrategy.class);
        return cls.getConstructor(LoggerConfig.class).newInstance(loggerConfig);
    } catch (final Exception dynamicFailed) {
        StatusLogger.getLogger().warn(
                "Could not create ReliabilityStrategy for '{}', using default AwaitCompletionReliabilityStrategy: {}", strategy, dynamicFailed);
        return new AwaitCompletionReliabilityStrategy(loggerConfig);
    }
}
 
Example #9
Source File: PropertiesConfigurationBuilder.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static <B extends ComponentBuilder<?>> B processRemainingProperties(final B builder,
                                                                            final Properties properties) {
    while (properties.size() > 0) {
        final String propertyName = properties.stringPropertyNames().iterator().next();
        final int index = propertyName.indexOf('.');
        if (index > 0) {
            final String prefix = propertyName.substring(0, index);
            final Properties componentProperties = PropertiesUtil.extractSubset(properties, prefix);
            builder.addComponent(createComponent(builder, prefix, componentProperties));
        } else {
            builder.addAttribute(propertyName, properties.getProperty(propertyName));
            properties.remove(propertyName);
        }
    }
    return builder;
}
 
Example #10
Source File: AbstractConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
protected void setToDefault() {
    // LOG4J2-1176 facilitate memory leak investigation
    setName(DefaultConfiguration.DEFAULT_NAME + "@" + Integer.toHexString(hashCode()));
    final Layout<? extends Serializable> layout = PatternLayout.newBuilder()
            .setPattern(DefaultConfiguration.DEFAULT_PATTERN)
            .setConfiguration(this)
            .build();
    final Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout);
    appender.start();
    addAppender(appender);
    final LoggerConfig rootLoggerConfig = getRootLogger();
    rootLoggerConfig.addAppender(appender, null, null);

    final Level defaultLevel = Level.ERROR;
    final String levelName = PropertiesUtil.getProperties().getStringProperty(DefaultConfiguration.DEFAULT_LEVEL,
            defaultLevel.name());
    final Level level = Level.valueOf(levelName);
    rootLoggerConfig.setLevel(level != null ? level : defaultLevel);
}
 
Example #11
Source File: Activator.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public void start(final BundleContext context) throws Exception {
    pluginRegistration = context.registerService(PluginService.class.getName(), new Log4jPlugins(),
            new Hashtable<>());
    final Provider provider = new Log4jProvider();
    final Hashtable<String, String> props = new Hashtable<>();
    props.put("APIVersion", "2.60");
    final ContextDataProvider threadContextProvider = new ThreadContextDataProvider();
    provideRegistration = context.registerService(Provider.class.getName(), provider, props);
    contextDataRegistration = context.registerService(ContextDataProvider.class.getName(), threadContextProvider,
            null);
    loadContextProviders(context);
    // allow the user to override the default ContextSelector (e.g., by using BasicContextSelector for a global cfg)
    if (PropertiesUtil.getProperties().getStringProperty(Constants.LOG4J_CONTEXT_SELECTOR) == null) {
        System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, BundleContextSelector.class.getName());
    }
    contextRef.compareAndSet(null, context);
}
 
Example #12
Source File: ClockFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static Clock createClock() {
    final String userRequest = PropertiesUtil.getProperties().getStringProperty(PROPERTY_NAME);
    if (userRequest == null) {
        LOGGER.trace("Using default SystemClock for timestamps.");
        return logSupportedPrecision(new SystemClock());
    }
    Supplier<Clock> specified = aliases().get(userRequest);
    if (specified != null) {
        LOGGER.trace("Using specified {} for timestamps.", userRequest);
        return logSupportedPrecision(specified.get());
    }
    try {
        final Clock result = Loader.newCheckedInstanceOf(userRequest, Clock.class);
        LOGGER.trace("Using {} for timestamps.", result.getClass().getName());
        return logSupportedPrecision(result);
    } catch (final Exception e) {
        final String fmt = "Could not create {}: {}, using default SystemClock for timestamps.";
        LOGGER.error(fmt, userRequest, e);
        return logSupportedPrecision(new SystemClock());
    }
}
 
Example #13
Source File: AbstractJpaAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public void tearDown() throws SQLException {
    final LoggerContext context = LoggerContext.getContext(false);
    try {
        String appenderName = "databaseAppender";
        final Appender appender = context.getConfiguration().getAppender(appenderName);
        assertNotNull("The appender '" + appenderName + "' should not be null.", appender);
        assertTrue("The appender should be a JpaAppender.", appender instanceof JpaAppender);
        ((JpaAppender) appender).getManager().close();
    } finally {
        System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
        PropertiesUtil.getProperties().reload();
        context.reconfigure();
        StatusLogger.getLogger().reset();

        try (Statement statement = this.connection.createStatement();) {
            statement.execute("SHUTDOWN");
        }

        this.connection.close();
    }
}
 
Example #14
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 #15
Source File: ThreadContext.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * <em>Consider private, used for testing.</em>
 */
static void init() {
    ThreadContextMapFactory.init();
    contextMap = null;
    final PropertiesUtil managerProps = PropertiesUtil.getProperties();
    boolean disableAll = managerProps.getBooleanProperty(DISABLE_ALL);
    useStack = !(managerProps.getBooleanProperty(DISABLE_STACK) || disableAll);
    boolean useMap = !(managerProps.getBooleanProperty(DISABLE_MAP) || disableAll);

    contextStack = new DefaultThreadContextStack(useStack);
    if (!useMap) {
        contextMap = new NoOpThreadContextMap();
    } else {
        contextMap = ThreadContextMapFactory.createThreadContextMap();
    }
    if (contextMap instanceof ReadOnlyThreadContextMap) {
        readOnlyContextMap = (ReadOnlyThreadContextMap) contextMap;
    } else {
        readOnlyContextMap = null;
    }
}
 
Example #16
Source File: SmtpManager.java    From logging-log4j2 with 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 #17
Source File: LoggerUtil.java    From Javacord with Apache License 2.0 5 votes vote down vote up
/**
 * Get or create a logger with the given name.
 *
 * @param name The name of the logger.
 * @return The logger with the given name.
 */
public static Logger getLogger(String name) {
    AtomicBoolean logWarning = new AtomicBoolean(false);
    initialized.updateAndGet(initialized -> {
        if (!initialized && !ProviderUtil.hasProviders()) {
            noLogger.set(true);
            logWarning.set(true);
        }
        return true;
    });

    if (noLogger.get()) {
        return loggers.computeIfAbsent(name, key -> {
            Level level = FallbackLoggerConfiguration.isTraceEnabled()
                    ? Level.TRACE
                    : (FallbackLoggerConfiguration.isDebugEnabled() ? Level.DEBUG : Level.INFO);
            Logger logger = new SimpleLogger(name, level, true, false, true, true, "yyyy-MM-dd HH:mm:ss.SSSZ", null,
                                             new PropertiesUtil(new Properties()), System.out);
            if (logWarning.get()) {
                logger.info("No Log4j2 compatible logger was found. Using default Javacord implementation!");
            }
            return new PrivacyProtectionLogger(logger);
        });
    } else {
        return new PrivacyProtectionLogger(LogManager.getLogger(name));
    }
}
 
Example #18
Source File: Log4j2CloudConfigLoggingSystem.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
protected String[] getStandardConfigLocations() {
    String[] locations = super.getStandardConfigLocations();
    PropertiesUtil props = new PropertiesUtil(new Properties());
    String location = props.getStringProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
    if (location != null) {
        List<String> list = Arrays.asList(super.getStandardConfigLocations());
        list.add(location);
        locations = list.toArray(new String[0]);
    }
    return locations;
}
 
Example #19
Source File: AsyncQueueFullPolicyFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Before
@After
public void resetProperties() throws Exception {
    System.clearProperty(AsyncQueueFullPolicyFactory.PROPERTY_NAME_ASYNC_EVENT_ROUTER);
    System.clearProperty(AsyncQueueFullPolicyFactory.PROPERTY_NAME_DISCARDING_THRESHOLD_LEVEL);
    PropertiesUtil.getProperties().reload();
}
 
Example #20
Source File: AbstractAsyncThreadContextTestBase.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
void init() {
    System.clearProperty("log4j2.threadContextMap");
    final String PACKAGE = "org.apache.logging.log4j.spi.";
    System.setProperty("log4j2.threadContextMap", PACKAGE + implClassSimpleName());
    PropertiesUtil.getProperties().reload();
    ThreadContextTestAccess.init();
}
 
Example #21
Source File: ThreadContextDataInjectorTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void prepareThreadContext(boolean isThreadContextMapInheritable) {
    System.setProperty("log4j2.isThreadContextMapInheritable", Boolean.toString(isThreadContextMapInheritable));
    PropertiesUtil.getProperties().reload();
    ThreadContextTest.reinitThreadContext();
    ThreadContext.remove("baz");
    ThreadContext.put("foo", "bar");
}
 
Example #22
Source File: AsyncQueueFullPolicyFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static AsyncQueueFullPolicy createDiscardingAsyncQueueFullPolicy() {
    final PropertiesUtil util = PropertiesUtil.getProperties();
    final String level = util.getStringProperty(PROPERTY_NAME_DISCARDING_THRESHOLD_LEVEL, Level.INFO.name());
    final Level thresholdLevel = Level.toLevel(level, Level.INFO);
    LOGGER.debug("Creating custom DiscardingAsyncQueueFullPolicy(discardThreshold:{})", thresholdLevel);
    return new DiscardingAsyncQueueFullPolicy(thresholdLevel);
}
 
Example #23
Source File: DisruptorUtil.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
static ExceptionHandler<AsyncLoggerConfigDisruptor.Log4jEventWrapper> getAsyncLoggerConfigExceptionHandler() {
    final String cls = PropertiesUtil.getProperties().getStringProperty("AsyncLoggerConfig.ExceptionHandler");
    if (cls == null) {
        return new AsyncLoggerConfigDefaultExceptionHandler();
    }
    try {
        @SuppressWarnings("unchecked")
        final Class<? extends ExceptionHandler<AsyncLoggerConfigDisruptor.Log4jEventWrapper>> klass =
                (Class<? extends ExceptionHandler<AsyncLoggerConfigDisruptor.Log4jEventWrapper>>) Loader.loadClass(cls);
        return klass.newInstance();
    } catch (final Exception ignored) {
        LOGGER.debug("Invalid AsyncLoggerConfig.ExceptionHandler value: error creating {}: ", cls, ignored);
        return new AsyncLoggerConfigDefaultExceptionHandler();
    }
}
 
Example #24
Source File: DisruptorUtil.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
static ExceptionHandler<RingBufferLogEvent> getAsyncLoggerExceptionHandler() {
    final String cls = PropertiesUtil.getProperties().getStringProperty("AsyncLogger.ExceptionHandler");
    if (cls == null) {
        return new AsyncLoggerDefaultExceptionHandler();
    }
    try {
        @SuppressWarnings("unchecked")
        final Class<? extends ExceptionHandler<RingBufferLogEvent>> klass =
            (Class<? extends ExceptionHandler<RingBufferLogEvent>>) Loader.loadClass(cls);
        return klass.newInstance();
    } catch (final Exception ignored) {
        LOGGER.debug("Invalid AsyncLogger.ExceptionHandler value: error creating {}: ", cls, ignored);
        return new AsyncLoggerDefaultExceptionHandler();
    }
}
 
Example #25
Source File: LoggerUtil.java    From Javacord with Apache License 2.0 5 votes vote down vote up
/**
 * Get or create a logger with the given name.
 *
 * @param name The name of the logger.
 * @return The logger with the given name.
 */
public static Logger getLogger(String name) {
    AtomicBoolean logWarning = new AtomicBoolean(false);
    initialized.updateAndGet(initialized -> {
        if (!initialized && !ProviderUtil.hasProviders()) {
            noLogger.set(true);
            logWarning.set(true);
        }
        return true;
    });

    if (noLogger.get()) {
        return loggers.computeIfAbsent(name, key -> {
            Level level = FallbackLoggerConfiguration.isTraceEnabled()
                    ? Level.TRACE
                    : (FallbackLoggerConfiguration.isDebugEnabled() ? Level.DEBUG : Level.INFO);
            Logger logger = new SimpleLogger(name, level, true, false, true, true, "yyyy-MM-dd HH:mm:ss.SSSZ", null,
                                             new PropertiesUtil(new Properties()), System.out);
            if (logWarning.get()) {
                logger.info("No Log4j2 compatible logger was found. Using default Javacord implementation!");
            }
            return new PrivacyProtectionLogger(logger);
        });
    } else {
        return new PrivacyProtectionLogger(LogManager.getLogger(name));
    }
}
 
Example #26
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 #27
Source File: PropertiesConfigurationBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private <B extends LoggableComponentBuilder<? extends ComponentBuilder<?>>> B addLoggersToComponent(
    final B loggerBuilder, final Properties properties) {
    final Map<String, Properties> appenderRefs = PropertiesUtil.partitionOnCommonPrefixes(
        PropertiesUtil.extractSubset(properties, "appenderRef"));
    for (final Map.Entry<String, Properties> entry : appenderRefs.entrySet()) {
        loggerBuilder.add(createAppenderRef(entry.getKey().trim(), entry.getValue()));
    }
    return loggerBuilder;
}
 
Example #28
Source File: PropertiesConfigurationBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private <B extends FilterableComponentBuilder<? extends ComponentBuilder<?>>> B addFiltersToComponent(
    final B componentBuilder, final Properties properties) {
    final Map<String, Properties> filters = PropertiesUtil.partitionOnCommonPrefixes(
        PropertiesUtil.extractSubset(properties, "filter"));
    for (final Map.Entry<String, Properties> entry : filters.entrySet()) {
        componentBuilder.add(createFilter(entry.getKey().trim(), entry.getValue()));
    }
    return componentBuilder;
}
 
Example #29
Source File: AbstractLogger.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static Class<? extends MessageFactory> createClassForProperty(final String property,
        final Class<ReusableMessageFactory> reusableParameterizedMessageFactoryClass,
        final Class<ParameterizedMessageFactory> parameterizedMessageFactoryClass) {
    try {
        final String fallback = Constants.ENABLE_THREADLOCALS ? reusableParameterizedMessageFactoryClass.getName()
                : parameterizedMessageFactoryClass.getName();
        final String clsName = PropertiesUtil.getProperties().getStringProperty(property, fallback);
        return LoaderUtil.loadClass(clsName).asSubclass(MessageFactory.class);
    } catch (final Throwable t) {
        return parameterizedMessageFactoryClass;
    }
}
 
Example #30
Source File: TerminalConsoleAppender.java    From TerminalConsoleAppender with MIT License 5 votes vote down vote up
private static @Nullable Boolean getOptionalBooleanProperty(String name) {
    String value = PropertiesUtil.getProperties().getStringProperty(name);
    if (value == null) {
        return null;
    }

    if (value.equalsIgnoreCase("true")) {
        return Boolean.TRUE;
    } else if (value.equalsIgnoreCase("false"))  {
        return Boolean.FALSE;
    } else {
        LOGGER.warn("Invalid value for boolean input property '{}': {}", name, value);
        return null;
    }
}