org.apache.logging.log4j.core.util.Constants Java Examples

The following examples show how to use org.apache.logging.log4j.core.util.Constants. 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: ConfigurationAssemblerTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildConfiguration() {
    try {
        System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
                "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
        final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory
                .newConfigurationBuilder();
        CustomConfigurationFactory.addTestFixtures("config name", builder);
        final Configuration configuration = builder.build();
        try (LoggerContext ctx = Configurator.initialize(configuration)) {
            validate(configuration);
        }
    } finally {
        System.getProperties().remove(Constants.LOG4J_CONTEXT_SELECTOR);
    }
}
 
Example #2
Source File: FailoverAppender.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Create a Failover Appender.
 * @param name The name of the Appender (required).
 * @param primary The name of the primary Appender (required).
 * @param failovers The name of one or more Appenders to fail over to (at least one is required).
 * @param retryIntervalSeconds The retry interval in seconds.
 * @param config The current Configuration (passed by the Configuration when the appender is created).
 * @param filter A Filter (optional).
 * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
 *               they are propagated to the caller.
 * @return The FailoverAppender that was created.
 */
@PluginFactory
public static FailoverAppender createAppender(
        @PluginAttribute @Required(message = "A name for the Appender must be specified") final String name,
        @PluginAttribute @Required(message = "A primary Appender must be specified") final String primary,
        @PluginElement @Required(message = "At least one failover Appender must be specified") final String[] failovers,
        @PluginAliases("retryInterval") // deprecated
        @PluginAttribute(defaultInt = DEFAULT_INTERVAL_SECONDS) final int retryIntervalSeconds,
        @PluginConfiguration final Configuration config,
        @PluginElement final Filter filter,
        @PluginAttribute(defaultBoolean = true) final boolean ignoreExceptions) {

    int retryIntervalMillis;
    if (retryIntervalSeconds >= 0) {
        retryIntervalMillis = retryIntervalSeconds * Constants.MILLIS_IN_SECONDS;
    } else {
        LOGGER.warn("Interval {} is less than zero. Using default", retryIntervalSeconds);
        retryIntervalMillis = DEFAULT_INTERVAL_SECONDS * Constants.MILLIS_IN_SECONDS;
    }
    return new FailoverAppender(name, filter, primary, failovers, retryIntervalMillis, config, ignoreExceptions, Property.EMPTY_ARRAY);
}
 
Example #3
Source File: FileManager.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a FileManager.
 * @param name The name of the File.
 * @param data The FactoryData
 * @return The FileManager for the File.
 */
@Override
public FileManager createManager(final String name, final FactoryData data) {
    final File file = new File(name);
    try {
        FileUtils.makeParentDirs(file);
        final int actualSize = data.bufferedIo ? data.bufferSize : Constants.ENCODER_BYTE_BUFFER_SIZE;
        final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[actualSize]);
        final FileOutputStream fos = data.createOnDemand ? null : new FileOutputStream(file, data.append);
        final boolean writeHeader = file.exists() && file.length() == 0;
        final FileManager fm = new FileManager(data.getLoggerContext(), name, fos, data.append, data.locking,
                data.createOnDemand, data.advertiseURI, data.layout,
                data.filePermissions, data.fileOwner, data.fileGroup, writeHeader, byteBuffer);
        if (fos != null && fm.attributeViewEnabled) {
            fm.defineAttributeView(file.toPath());
        }
        return fm;
    } catch (final IOException ex) {
        LOGGER.error("FileManager (" + name + ") " + ex, ex);
    }
    return null;
}
 
Example #4
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 #5
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 #6
Source File: LogEventFactoryTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            System.setProperty(Constants.LOG4J_LOG_EVENT_FACTORY, TestLogEventFactory.class.getName());
            resetLogEventFactory(new TestLogEventFactory());
            try {
                base.evaluate();
            } finally {
                System.clearProperty(Constants.LOG4J_LOG_EVENT_FACTORY);
                resetLogEventFactory(new DefaultLogEventFactory());
            }
        }

        private void resetLogEventFactory(final LogEventFactory logEventFactory) throws IllegalAccessException {
            final Field field = FieldUtils.getField(LoggerConfig.class, "LOG_EVENT_FACTORY", true);
            FieldUtils.removeFinalModifier(field, true);
            FieldUtils.writeStaticField(field, logEventFactory, false);
        }
    };
}
 
Example #7
Source File: ConfigurationAssemblerTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildConfiguration() throws Exception {
    try {
        System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
                "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
        final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory
                .newConfigurationBuilder();
        CustomConfigurationFactory.addTestFixtures("config name", builder);
        final Configuration configuration = builder.build();
        try (LoggerContext ctx = Configurator.initialize(configuration)) {
            validate(configuration);
        }
    } finally {
        System.getProperties().remove(Constants.LOG4J_CONTEXT_SELECTOR);
    }
}
 
Example #8
Source File: JsonTemplateLayout.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static Supplier<Context> createContextSupplier(
        final Charset charset,
        final JsonWriter jsonWriter) {
    return () -> {
        final JsonWriter clonedJsonWriter = jsonWriter.clone();
        final Encoder<StringBuilder> encoder =
                Constants.ENABLE_DIRECT_ENCODERS
                        ? new LockingStringBuilderEncoder(charset)
                        : null;
        return new Context(clonedJsonWriter, encoder);
    };
}
 
Example #9
Source File: LoggerContextRule.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public Statement apply(final Statement base, final Description description) {
    // Hack: Using -DEBUG as a JVM param sets a property called "EBUG"...
    if (System.getProperties().containsKey("EBUG")) {
        StatusLogger.getLogger().setLevel(Level.DEBUG);
    }
    testClassName = description.getClassName();
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            if (contextSelectorClass != null) {
                System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, contextSelectorClass.getName());
            }
            // TODO Consider instead of the above:
            // LogManager.setFactory(new Log4jContextFactory(LoaderUtil.newInstanceOf(contextSelectorClass)));
            System.setProperty(SYS_PROP_KEY_CLASS_NAME, description.getClassName());
            System.setProperty(SYS_PROP_KEY_DISPLAY_NAME, description.getDisplayName());
            loggerContext = Configurator.initialize(description.getDisplayName(),
                    description.getTestClass().getClassLoader(), configurationLocation);
            try {
                base.evaluate();
            } finally {
                if (!Configurator.shutdown(loggerContext, shutdownTimeout, shutdownTimeUnit)) {
                    StatusLogger.getLogger().error("Logger context {} did not shutdown completely after {} {}.",
                            loggerContext.getName(), shutdownTimeout, shutdownTimeUnit);
                }
                loggerContext = null;
                contextSelectorClass = null;
                StatusLogger.getLogger().reset();
                System.clearProperty(Constants.LOG4J_CONTEXT_SELECTOR);
                System.clearProperty(SYS_PROP_KEY_CLASS_NAME);
                System.clearProperty(SYS_PROP_KEY_DISPLAY_NAME);
            }
        }
    };

}
 
Example #10
Source File: MessagePatternConverter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Private constructor.
 *
 * @param options
 *            options, may be null.
 */
private MessagePatternConverter(final Configuration config, final String[] options) {
    super("Message", "message");
    this.formats = options;
    this.config = config;
    final int noLookupsIdx = loadNoLookups(options);
    this.noLookups = Constants.FORMAT_MESSAGES_PATTERN_DISABLE_LOOKUPS || noLookupsIdx >= 0;
    this.textRenderer = loadMessageRenderer(noLookupsIdx >= 0 ? ArrayUtils.remove(options, noLookupsIdx) : options);
}
 
Example #11
Source File: AbstractOutputStreamAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void tryAppend(final LogEvent event) {
    if (Constants.ENABLE_DIRECT_ENCODERS) {
        directEncodeEvent(event);
    } else {
        writeByteArrayToManager(event);
    }
}
 
Example #12
Source File: AbstractStringLayout.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a new layout.
 * @param aCharset the charset used to encode the header bytes, footer bytes and anything else that needs to be
 *      converted from strings to bytes.
 * @param header the header bytes
 * @param footer the footer bytes
 */
protected AbstractStringLayout(final Charset aCharset, final byte[] header, final byte[] footer) {
    super(null, header, footer);
    this.headerSerializer = null;
    this.footerSerializer = null;
    this.charset = aCharset == null ? StandardCharsets.UTF_8 : aCharset;
    this.charsetName = this.charset.name();
    useCustomEncoding = isPreJava8()
            && (StandardCharsets.ISO_8859_1.equals(aCharset) || StandardCharsets.US_ASCII.equals(aCharset));
    textEncoder = Constants.ENABLE_DIRECT_ENCODERS ? new StringBuilderEncoder(charset) : null;
}
 
Example #13
Source File: AbstractStringLayout.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a new layout.
 * @param config the configuration
 * @param aCharset the charset used to encode the header bytes, footer bytes and anything else that needs to be
 *      converted from strings to bytes.
 * @param headerSerializer the header bytes serializer
 * @param footerSerializer the footer bytes serializer
 */
protected AbstractStringLayout(final Configuration config, final Charset aCharset,
        final Serializer headerSerializer, final Serializer footerSerializer) {
    super(config, null, null);
    this.headerSerializer = headerSerializer;
    this.footerSerializer = footerSerializer;
    this.charset = aCharset == null ? StandardCharsets.UTF_8 : aCharset;
    this.charsetName = this.charset.name();
    useCustomEncoding = isPreJava8()
            && (StandardCharsets.ISO_8859_1.equals(aCharset) || StandardCharsets.US_ASCII.equals(aCharset));
    textEncoder = Constants.ENABLE_DIRECT_ENCODERS ? new StringBuilderEncoder(charset) : null;
}
 
Example #14
Source File: DatePatternConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public DatePatternConverterTest(final Boolean threadLocalEnabled) throws Exception {
    // Setting the system property does not work: the Constant field has already been initialized...
    //System.setProperty("log4j2.enable.threadlocals", threadLocalEnabled.toString());

    final Field field = Constants.class.getDeclaredField("ENABLE_THREADLOCALS");
    field.setAccessible(true); // make non-private

    final Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); // make non-final

    field.setBoolean(null, threadLocalEnabled.booleanValue());
}
 
Example #15
Source File: XmlConfigurationPropsTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultStatus() {
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG1);
    System.setProperty(Constants.LOG4J_DEFAULT_STATUS_LEVEL, "WARN");
    try {
        final LoggerContext ctx = LoggerContext.getContext();
        ctx.reconfigure();
        final Configuration config = ctx.getConfiguration();
        assertTrue("Configuration is not an XmlConfiguration", config instanceof XmlConfiguration);
    } finally {
        System.clearProperty(Constants.LOG4J_DEFAULT_STATUS_LEVEL);
    }
}
 
Example #16
Source File: ConfigurationAssemblerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildConfiguration() throws Exception {
    try {
        System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
                "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
        final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
        CustomConfigurationFactory.addTestFixtures("config name", builder);
        final Configuration configuration = builder.build();
        try (LoggerContext ctx = Configurator.initialize(configuration)) {
            validate(configuration);
        }
    } finally {
        System.getProperties().remove(Constants.LOG4J_CONTEXT_SELECTOR);
    }
}
 
Example #17
Source File: ConfigurationAssemblerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomConfigurationFactory() throws Exception {
    try {
        System.setProperty(ConfigurationFactory.CONFIGURATION_FACTORY_PROPERTY,
                "org.apache.logging.log4j.core.config.builder.CustomConfigurationFactory");
        System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
                "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
        final Configuration config = ((LoggerContext) LogManager.getContext(false)).getConfiguration();
        validate(config);
    } finally {
        System.getProperties().remove(Constants.LOG4J_CONTEXT_SELECTOR);
        System.getProperties().remove(ConfigurationFactory.CONFIGURATION_FACTORY_PROPERTY);
    }
}
 
Example #18
Source File: AsyncLoggerTestCachedThreadName.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "AsyncLoggerTest.xml");
}
 
Example #19
Source File: Log4j2Jira1688AsyncTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "log4j-list.xml");
}
 
Example #20
Source File: AbstractAsyncThreadContextTestBase.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void afterClass() {
    System.clearProperty("AsyncLogger.RingBufferSize");
    System.clearProperty("AsyncLoggerConfig.RingBufferSize");
    System.clearProperty(Constants.LOG4J_CONTEXT_SELECTOR);
    System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
    System.clearProperty("log4j2.garbagefree.threadContextMap");
    System.clearProperty("log4j2.is.webapp");
    System.clearProperty("log4j2.threadContextMap");
}
 
Example #21
Source File: AbstractAsyncThreadContextTestBase.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
void initSelector() {
    if (this == ALL_ASYNC || this == BOTH_ALL_ASYNC_AND_MIXED) {
        System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,  AsyncLoggerContextSelector.class.getName());
    } else {
        System.clearProperty(Constants.LOG4J_CONTEXT_SELECTOR);
    }
}
 
Example #22
Source File: AsyncLoggerTestUncachedThreadName.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    System.setProperty("AsyncLogger.ThreadNameStrategy", "UNCACHED");
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "AsyncLoggerTest.xml");
}
 
Example #23
Source File: AsyncLoggerTestNanoTime.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "NanoTimeToFileTest.xml");
}
 
Example #24
Source File: AsyncLoggerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "AsyncLoggerTest.xml");
}
 
Example #25
Source File: AsyncLoggerUseAfterShutdownTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "AsyncLoggerTest.xml");
}
 
Example #26
Source File: AsyncLoggerLocationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    final File file = new File("target", "AsyncLoggerLocationTest.log");
    file.delete();
    
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "AsyncLoggerLocationTest.xml");
}
 
Example #27
Source File: AsyncLoggerThreadContextTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "AsyncLoggerThreadContextTest.xml");
}
 
Example #28
Source File: AsyncLoggerCustomSelectorLocationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    final File file = new File("target", "AsyncLoggerCustomSelectorLocationTest.log");
    file.delete();
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            CustomAsyncContextSelector.class.getName());
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "AsyncLoggerCustomSelectorLocationTest.xml");
}
 
Example #29
Source File: AsyncLoggerTimestampMessageTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "AsyncLoggerTimestampMessageTest.xml");
    System.setProperty(ClockFactory.PROPERTY_NAME,
            PoisonClock.class.getName());
}
 
Example #30
Source File: AsyncLoggerTestArgumentFreedOnError.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    System.setProperty("log4j2.enable.threadlocals", "true");
    System.setProperty("log4j2.enable.direct.encoders", "true");
    System.setProperty("log4j2.is.webapp", "false");
    System.setProperty("log4j.format.msg.async", "true");
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
}