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

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

源代码1 项目: pulsar   文件: ConfigurationAssemblerTest.java
@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);
    }
}
 
@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);
    }
}
 
源代码3 项目: logging-log4j2   文件: Activator.java
@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);
}
 
源代码4 项目: logging-log4j2   文件: FileManager.java
/**
 * 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;
}
 
源代码5 项目: logging-log4j2   文件: FailoverAppender.java
/**
 * 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);
}
 
源代码6 项目: logging-log4j2   文件: DisruptorUtil.java
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);
}
 
源代码7 项目: logging-log4j2   文件: LogEventFactoryTest.java
@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);
        }
    };
}
 
源代码8 项目: pulsar   文件: ConfigurationAssemblerTest.java
@Test
public void testCustomConfigurationFactory() {
    try {
        System.setProperty(ConfigurationFactory.CONFIGURATION_FACTORY_PROPERTY,
                "org.apache.pulsar.log4j2.appender.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);
    }
}
 
@Override
void setUp() throws Exception {
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    logger = LogManager.getLogger("RAFExtendedException");
    if (!AsyncLoggerContext.class.equals(LogManager.getContext(false).getClass())) {
        throw new IllegalStateException("Expected an AsyncLoggerContext");
    }
}
 
@Override
void setUp() throws Exception {
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    logger = LogManager.getLogger("RAFSimpleException");
    if (!AsyncLoggerContext.class.equals(LogManager.getContext(false).getClass())) {
        throw new IllegalStateException("Expected an AsyncLoggerContext");
    }
}
 
源代码11 项目: logging-log4j2   文件: DemoAppender.java
@Override
public void append(final LogEvent event) {
    if (Constants.ENABLE_DIRECT_ENCODERS) {
        getLayout().encode(event, this);
        drain(byteBuffer);
    } else {
        final byte[] binary = getLayout().toByteArray(event);
        consume(binary, 0, binary.length);
    }
}
 
@BeforeClass
public static void beforeClass() {
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "AsyncLoggerTest.xml");
}
 
源代码13 项目: logging-log4j2   文件: JsonTemplateLayout.java
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);
    };
}
 
@Test
public void testCustomConfigurationFactory() throws Exception {
    try {
        System.setProperty(ConfigurationFactory.CONFIGURATION_FACTORY_PROPERTY,
                "org.apache.logging.log4j.kafka.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);
    }
}
 
源代码15 项目: logging-log4j2   文件: MessagePatternConverter.java
/**
 * 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);
}
 
源代码16 项目: logging-log4j2   文件: DatePatternConverter.java
private MutableInstant getMutableInstant() {
    if (Constants.ENABLE_THREADLOCALS) {
        MutableInstant result = threadLocalMutableInstant.get();
        if (result == null) {
            result = new MutableInstant();
            threadLocalMutableInstant.set(result);
        }
        return result;
    }
    return new MutableInstant();
}
 
源代码17 项目: logging-log4j2   文件: DatePatternConverter.java
public void format(final Instant instant, final StringBuilder output) {
    if (Constants.ENABLE_THREADLOCALS) {
        formatWithoutAllocation(instant, output);
    } else {
        formatWithoutThreadLocals(instant, output);
    }
}
 
源代码18 项目: logging-log4j2   文件: JndiContextSelector.java
private String getContextName() {
    String loggingContextName = null;

    try (final JndiManager jndiManager = JndiManager.getDefaultManager()) {
        loggingContextName = jndiManager.lookup(Constants.JNDI_CONTEXT_NAME);
    } catch (final NamingException ne) {
        LOGGER.error("Unable to lookup {}", Constants.JNDI_CONTEXT_NAME, ne);
    }
    return loggingContextName;
}
 
源代码19 项目: logging-log4j2   文件: AbstractConfiguration.java
protected Level getDefaultStatus() {
    final String statusLevel = PropertiesUtil.getProperties().getStringProperty(
            Constants.LOG4J_DEFAULT_STATUS_LEVEL, Level.ERROR.name());
    try {
        return Level.toLevel(statusLevel);
    } catch (final Exception ex) {
        return Level.ERROR;
    }
}
 
源代码20 项目: logging-log4j2   文件: Log4jContextFactory.java
private static ContextSelector createContextSelector() {
    try {
        final ContextSelector selector = Loader.newCheckedInstanceOfProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            ContextSelector.class);
        if (selector != null) {
            return selector;
        }
    } catch (final Exception e) {
        LOGGER.error("Unable to create custom ContextSelector. Falling back to default.", e);
    }
    return new ClassLoaderContextSelector();
}
 
源代码21 项目: logging-log4j2   文件: SyslogAppender.java
@SuppressWarnings({"resource", "unchecked"})
@Override
public SyslogAppender build() {
    final Protocol protocol = getProtocol();
    final SslConfiguration sslConfiguration = getSslConfiguration();
    final boolean useTlsMessageFormat = sslConfiguration != null || protocol == Protocol.SSL;
    final Configuration configuration = getConfiguration();
    Layout<? extends Serializable> layout = getLayout();
    if (layout == null) {
        layout = RFC5424.equalsIgnoreCase(format)
                ? Rfc5424Layout.createLayout(facility, id, enterpriseNumber, includeMdc, mdcId, mdcPrefix,
                        eventPrefix, newLine, escapeNL, appName, msgId, excludes, includes, required,
                        exceptionPattern, useTlsMessageFormat, loggerFields, configuration)
                :
                // @formatter:off
                SyslogLayout.newBuilder()
                    .setFacility(facility)
                    .setIncludeNewLine(newLine)
                    .setEscapeNL(escapeNL)
                    .setCharset(charsetName)
                    .build();
                // @formatter:off
    }
    final String name = getName();
    if (name == null) {
        LOGGER.error("No name provided for SyslogAppender");
        return null;
    }
    final AbstractSocketManager manager = createSocketManager(name, protocol, getHost(), getPort(), getConnectTimeoutMillis(),
            sslConfiguration, getReconnectDelayMillis(), getImmediateFail(), layout, Constants.ENCODER_BYTE_BUFFER_SIZE, null);

    return new SyslogAppender(name, layout, getFilter(), isIgnoreExceptions(), isImmediateFlush(), manager,
            getAdvertise() ? configuration.getAdvertiser() : null);
}
 
private void tryAppend(final LogEvent event) {
    if (Constants.ENABLE_DIRECT_ENCODERS) {
        directEncodeEvent(event);
    } else {
        writeByteArrayToManager(event);
    }
}
 
源代码23 项目: logging-log4j2   文件: AbstractStringLayout.java
/**
 * 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;
}
 
源代码24 项目: logging-log4j2   文件: AbstractStringLayout.java
/**
 * 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;
}
 
源代码25 项目: logging-log4j2   文件: LoggerContextRule.java
@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);
            }
        }
    };

}
 
源代码26 项目: logging-log4j2   文件: DatePatternConverterTest.java
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());
}
 
源代码27 项目: logging-log4j2   文件: XmlConfigurationPropsTest.java
@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);
    }
}
 
@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);
    }
}
 
@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);
    }
}
 
@BeforeClass
public static void beforeClass() {
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "AsyncLoggerTest.xml");
}
 
 类所在包
 同包方法