Configuration properties

Log4j contains a simple configuration properties sub-system that aggregates data from multiple property sources, such as Java System Properties and Environment Variables. See Property sources for a complete list of supported sources.

Configuration properties are used by Log4j in the following situations:

  • to finely tune Log4j API and Log4j Core services that are independent of the configuration file,

  • to change the default values of attributes used in a configuration file.

Log4j 3 introduces significant changes in the configuration properties subsystem by adding support for logger context specific properties. Two kinds of configuration properties can be used:

Logger context scoped properties

These properties apply only to a single logger context. If <contextName> is the name of a logger context, it can be tuned using properties of the form:

log4j.contexts.<contextName>.propertyName

If the configuration property is specified using environment variables, the naming convention used is:

LOG4J_CONTEXTS_<contextName>_PROPERTY_NAME

Not all configuration properties can be used this way. Properties that specify global Log4j services, such as the logging provider used, can not be restricted to a single logger context.

Global configuration properties

Global configuration properties can be used to provide a default value for context scoped properties described above. Their generic syntax is:

log4j.propertyName

where propertyName is a sequence of camelcase words separated by dots. As usual, the environment variable property source adopts a different convention:

LOG4J_PROPERTY_NAME

You can specify configuration properties using a log4j2.component.properties resource at the root of your classpath. The configuration properties sub-system will take care of merging the content of all these resources.

The names of all configuration properties changed between Log4j 2 and Log4j 3.

To help users with the migration process the properties described in Log4j 2 configuration properties are still supported through a backward-compatibility mechanism. This mechanism is based on META-INF/log4j/propertyMapping.json classpath resources.

Users that use shading in their applications should take care of removing all META-INF/log4j/propertyMapping.json resources and use only Log4j 3 property names.

Since Log4j Core 3 uses Log4j API 2 to support global configuration properties, these properties are looked up using a fuzzy matching algorithm.

In case of problems with the properties sub-system, make sure that your application does not use property names with the following case-insensitive prefixes:

  • asyncLogger,

  • disableThreadContext,

  • isThreadContext,

  • org.apache.logging.log4j

and that all the properties names that start with log4j use the normalized form provided by the tables below.

Meta configuration properties

In order to rapidly optimize Log4j Core for a particular usage, you can use the following properties:

log4j.isWebapp

Env. variable

LOG4J_IS_WEBAPP

Type

boolean

Default value

true if the Servlet class on classpath,

false otherwise

Setting this property to true switches Log4j Core into "Web application mode" ("Web-app mode").

In this mode Log4j is optimized to work in a Servlet container.

This mode is incompatible with log4j.enableThreadlocals.

log4j.enableThreadlocals

Env. variable

LOG4J_ENABLE_THREADLOCALS

Type

boolean

Default value

false if Web-app mode is enabled,

true otherwise

Setting this property to true switches Log4j Core into "garbage-free mode" ("GC-free mode").

In this mode Log4j uses ThreadLocals for object pooling to prevent object allocations.

ThreadLocal fields holding non-JDK classes can cause memory leaks in web applications when the application server’s thread pool continues to reference these fields after the web application is undeployed. Hence, to avoid causing memory leaks, log4j2.enableThreadlocals by default reflects the opposite of log4j.isWebapp.

Log4j API properties

In order to configure Log4j API, see the Log4j 2 site.

Log4j Core properties

While the only required configuration of the log4j-core library is provided by the configuration file, the library offers many configuration properties that can be used to finely tune the way it works.

Async components

The behavior of all three async components (AsyncLogger, AsyncLoggerConfig and AsyncAppender) can be tuned using these properties:

log4j.async.formatMessagesInBackground

Env. variable

LOG4J_ASYNC_FORMAT_MESSAGES_IN_BACKGROUND

Type

boolean

Default value

false

If false, Log4j will make sure the message is formatted in the caller thread, otherwise the formatting will occur on the asynchronous thread.

Remark: messages annotated with AsynchronouslyFormattable will be formatted on the async thread regardless of this setting.

log4j.async.queueFullPolicy.type

Env. variable

LOG4J_ASYNC_QUEUE_FULL_POLICY_TYPE

Type

Class<? extends AsyncQueueFullPolicy> or predefined constant

Default value

Default

Determines the AsyncQueueFullPolicy to use when the underlying async component cannot keep up with the logging rate and the queue is filling up.

Its value should be the fully qualified class name of an AsyncQueueFullPolicy implementation or one of these predefined constants:

Default

blocks the calling thread until the event can be added to the queue.

Discard

when the queue is full, it drops the events whose level is equal or less than the threshold level (see log4j.async.queueFullPolicy.discardThreshold).

log4j.async.queueFullPolicy.discardThreshold

Env. variable

LOG4J_ASYNC_QUEUE_FULL_POLICY_DISCARD_THRESHOLD

Type

Level

Default value

INFO

Determines the threshold level used by a Discard queue full policy. Log events whose level is not more severe than the threshold level will be discarded during a queue full event. See also log4j.async.queueFullPolicy.type.

Logger context

The ContextSelector component specifies the strategy used by Log4j to create new logger contexts. The choice of ContextSelector determines in particular:

It can be customized using these properties:

log4j.loggerContext.selector

Env. variable

LOG4J_LOGGER_CONTEXT_SELECTOR

Type

Class<? extends ContextSelector>

Default value

ClassLoaderContextSelector

(on Android) BasicContextSelector

Specifies the fully qualified class name of the ContextSelector implementation to use.

A ContextSelector decides:

  • how loggers are split among logger contexts,

  • the Logger implementation to use.

The implementations available by default are:

org.apache.logging.log4j.core.selector.BasicContextSelector

Creates a single logger context and synchronous loggers

org.apache.logging.log4j.core.async.BasicAsyncLoggerContextSelector

Creates a single logger context and asynchronous loggers

org.apache.logging.log4j.core.selector.ClassLoaderContextSelector

Creates a separate logger context per classloader and synchronous loggers

org.apache.logging.log4j.core.async.AsyncLoggerContextSelector

Creates a separate logger context per classloader and asynchronous loggers

org.apache.logging.log4j.core.osgi.BundleContextSelector

Creates a separate logger context per OSGi bundle and synchronous loggers

org.apache.logging.log4j.jndi.selector.JndiContextSelector

Creates loggers contexts based on a JNDI lookup and synchronous loggers. See Web application for details.

log4j.loggerContext.shutdownHookEnabled

Env. variable

LOG4J_LOGGER_CONTEXT_SHUTDOWN_HOOK_ENABLED

Type

boolean

Default value

true

(Web-app mode: false)

If true a shutdown hook will be installed to stop the logger context when the system stops.

log4j.loggerContext.shutdownCallbackRegistry

Env. variable

LOG4J_LOGGER_CONTEXT_SHUTDOWN_CALLBACK_REGISTRY

Type

Class<? extends ShutdownCallbackRegistry>

Default value

DefaultShutdownCallbackRegistry

The fully qualified class name of a ShutdownCallbackRegistry implementation. Integrators can use this to customize the shutdown order of the JVM.

The default implementation executes all shutdown actions in a separate Thread registered through Runtime#addShutdownHook().

log4j.loggerContext.stacktraceOnStart

Env. variable

LOG4J_LOGGER_CONTEXT_STACKTRACE_ON_START

Type

boolean

Default value

false

Prints a stacktrace to the status logger at DEBUG level when the LoggerContext is started.

For debug purposes only.

Configuration factory

Since configuration factories are used to parse the configuration file, they can only be configured through global configuration properties.

Log4j Core supports both local and remote configuration files. If a remote configuration file is used, its transport must be secured. See Transport security for details.

log4j.configuration.factory

Env. variable

LOG4J_CONFIGURATION_FACTORY

Type

Class<? extends ConfigurationFactory>

Default value

null

Specifies the fully qualified class name of the preferred ConfigurationFactory to use.

Log4j will attempt to use the provided configuration factory before any other factory implementation.

log4j.configuration.location

Env. variable

LOG4J_CONFIGURATION_LOCATION

Type

Comma-separated list of Paths or URIs

Default value

automatically detected

Specifies a comma-separated list of URIs or file paths to Log4j 2 configuration files.

If a relative URL is provided, it is interpreted as:

  • path to a file, if the file exists,

  • a classpath resource otherwise.

Usage of absolute URLs is restricted by the Transport Security configuration options.

log4j.configuration.level

Env. variable

LOG4J_LEVEL

Type

Level

Default value

ERROR

Specifies the level of the root logger if:

  • the default configuration is used,

  • or the configuration file does not specify a level for the root logger.

log4j.configuration.mergeStrategy

Env. variable

LOG4J_MERGE_STRATEGY

Type

Class<? extends MergeStrategy>

Default value

DefaultMergeStrategy

Specifies the fully qualified class name of the MergeStrategy implementation used to merge multiple configuration files into one.

Log messages

The way Log4j builds Messages can be customized using these properties:

log4j.message.factory

Env. variable

LOG4J_MESSAGE_FACTORY

Type

Class<? extends MessageFactory>

Default value

ReusableMessageFactory

Fully qualified class name of a MessageFactory implementation that will be used by loggers if no explicit factory was specified.

Log events

The way Log4j builds LogEvents can be customized using these properties:

log4j.logEvent.contextData.type

Env. variable

LOG4J_LOG_EVENT_CONTEXT_DATA_TYPE

Type

Class<? extends StringMap>

Default value

SortedArrayStringMap

Fully qualified class name of a StringMap implementation to use to store context data in log events. The implementation must have:

  • a no-arg constructor,

  • a constructor accepting a single int parameter that specifies the capacity of the string map.

log4j.logEvent.contextData.injector

Env. variable

LOG4J_LOG_EVENT_CONTEXT_DATA_INJECTOR

Type

Class<? extends ContextDataInjector>

Default value

depends on the ThreadContextMap implementation

Fully qualified class name of a ContextDataInjector implementation.

The default implementation uses all implementations of ContextDataProvider registered with ServiceLoader.

log4j.logEvent.factory

Env. variable

LOG4J_LOG_EVENT_FACTORY

Type

Class<? extends LogEventFactory>

Default value

ReusableLogEventFactory

Specifies the LogEventFactory implementation to use to create log events.

Garbage Collection

log4j.gc.enableDirectEncoders

Env. variable

LOG4J_GC_ENABLE_DIRECT_ENCODERS

Type

boolean

Default value

true

If true, garbage-aware layouts will directly encode log events into ByteBuffers provided by appenders.

This prevents allocating temporary String and char[] instances.

log4j.gc.encoderByteBufferSize

Env. variable

LOG4J_GC_ENCODER_BYTE_BUFFER_SIZE

Type

int

Default value

8192

The size in bytes of the ByteBuffers stored in ThreadLocal fields by layouts and StringBuilderEncoders.

This setting is only used if log4j.gc.enableDirectEncoders is set to true.

log4j.gc.encoderCharBufferSize

Env. variable

LOG4J_GC_ENCODER_CHAR_BUFFER_SIZE

Type

int

Default value

4096

The size in chars of the ByteBuffers stored in ThreadLocal fields StringBuilderEncoders.

This setting is only used if log4j.gc.enableDirectEncoders is set to true.

log4j.gc.initialReusableMsgSize

Env. variable

LOG4J_GC_INITIAL_REUSABLE_MSG_SIZE

Type

int

Default value

128

In GC-free mode, this property determines the initial size of the reusable StringBuilders used by ReusableMessages for formatting purposes.

log4j.gc.maxReusableMsgSize

Env. variable

LOG4J_GC_MAX_REUSABLE_MSG_SIZE

Type

int

Default value

518

In GC-free mode, this property determines the maximum size of the reusable StringBuilders used by ReusableMessages for formatting purposes.

The default value allows is equal to 2 × (2 × log4j.initialReusableMsgSize + 2) + 2 and allows the StringBuilder to be resized twice by the current JVM resize algorithm.

log4j.gc.layoutStringBuilderMaxSize

Env. variable

LOG4J_GC_LAYOUT_STRING_BUILDER_MAX_SIZE

Type

int

Default value

2048

This property determines the maximum size of the reusable StringBuilders used to format LogEvents.

log4j2.unboxRingbufferSize

Env. variable

LOG4J_UNBOX_RINGBUFFER_SIZE

Type

int

Default value

32

The Unbox utility class can be used by users to format primitive values without incurring in the boxing allocation cost.

This property specifies the maximum number of primitive arguments to a log message that will be cached and usually does not need to be changed.

log4j.recycler.capacity

Env. variable

LOG4J_RECYCLER_CAPACITY

Type

int

Default value

2C rounded to the next power of 2 (C denoting the number of available processors)

Denotes the buffer capacity for a recycler. For a queueing recycler, it corresponds to the queue size. For a thread local recycler, it corresponds to the per-thread buffer size.

If an invalid capacity is provided (i.e., if the capacity is zero or negative), the default value will be used.

log4j.recycler.factory

Env. variable

LOG4J_RECYCLER_FACTORY

Type

String

Default value

null

If provided, available recycler factory providers will be sorted in order, and the first one whose name matching with this property value will be used.

If missing or the selection fails, the default will be used.

log4j.recycler.conversant.spinPolicy

Env. variable LOG4J_RECYCLER_CONVERSANT_SPIN_POLICY

Type

SpinPolicy

Default value

WAITING

Denotes the strategy adopted by the Conversant Disruptor, when the queue is fully used. This configuration property is only used if the conversant-disrutor recycler is used.

See Conversant Disruptor Javadoc for details.

Thread context

To configure the thread context used by Log4j Core, you can use the following properties:

These configuration properties are only used by Log4j Core and Simple Logger of Log4j API.

The log4j-to-slf4j logging bridge delegates ThreadContext calls to the SLF4J MDC class.

The log4j-to-jul logging bridge ignores all ThreadContext method calls.

log4j.threadContext.enable

Env. variable

LOG4J_THREAD_CONTEXT_ENABLE

Type

boolean

Default value

true

If false, the ThreadContext stack and map are disabled.

log4j.threadContext.enableStack

Env. variable

LOG4J_THREAD_CONTEXT_ENABLE_STACK

Type

boolean

Default value

true

If false, the ThreadContext stack is disabled.

log4j.threadContext.map.enable

Env. variable

LOG4J_THREAD_CONTEXT_MAP_ENABLE

Type

boolean

Default value

true

If false, the ThreadContext map is disabled.

log4j.threadContext.map.type

Env. variable

LOG4J_THREAD_CONTEXT_MAP_TYPE

Type

Class<? extends ThreadContextMap> or predefined constant

Default value

WebApp

Fully specified class name of a custom ThreadContextMap implementation class or one of the predefined constants:

NoOp

to disable the thread context,

WebApp

a web application-safe implementation, that only binds JRE classes to ThreadLocal to prevent memory leaks,

GarbageFree

a garbage-free implementation.

log4j.threadContext.map.garbageFree

Env. variable

LOG4J_THREAD_CONTEXT_MAP_GARBAGE_FREE

Default value

false

If set to true selects a garbage-free thread context map implementation.

Transport security

Since configuration files can be used to load arbitrary classes into a Log4j Core Configuration, users need to ensure that all the configuration elements come from trusted sources (cf. Thread model for more information).

In order to protect the user Log4j disables the http URI scheme by default and provides several configuration options to ensure secure transport of configuration files:

log4j.auth.provider

Env. variable

LOG4J_AUTH_PROVIDER

Type

Class<? extends AuthorizationProvider>

Default value

BasicAuthorizationProvider

The fully qualified class name of the AuthorizationProvider implementation to use with http and https URL protocols.

log4j.auth.basic.password

Env. variable

LOG4J_AUTH_BASIC_PASSWORD

Type

String

Default value

null

The password to use in HTTP Basic authentication.

If used in conjunction with log4j.auth.basic.passwordDecryptor the contents of this variable are interpreted by the decryptor.

log4j.auth.basic.passwordDecryptor

Env. variable

LOG4J_AUTH_BASIC_PASSWORD_DECRYPTOR

Type

Class<? extends PasswordDecryptor>

Default value

null

Fully qualified class name of an implementation of PasswordDecryptor to use for the value of the log4j.auth.basic.password property.

If null, the literal value of the password is used.

log4j.auth.basic.username

Env. variable

LOG4J_AUTH_BASIC_USERNAME

Type

String

Default value

null

The username used in HTTP Basic authentication.

log4j.configuration.allowedProtocols

Env. variable

LOG4J_CONFIGURATION_ALLOWED_PROTOCOLS

Type

Comma-separated list of URL protocols

Default value

file, https, jar

A comma separated list of URL protocols that may be used to load any kind of configuration source.

To completely prevent accessing the configuration via the Java URL class specify a value of _none.

NOTE

Since Log4j does not use URL to access file: resources, this protocol can not be effectively disabled.

log4j.transportSecurity.trustStore.location

Env. variable

LOG4J_TRANSPORT_SECURITY_TRUST_STORE_LOCATION

Type

Path or URI

Default value

see Default Java trust store

The location of the trust store.

log4j.transportSecurity.trustStore.password

Env. variable

LOG4J_TRANSPORT_SECURITY_TRUST_STORE_PASSWORD

Type

String

Default value

null

The password for the trust store.

log4j.transportSecurity.trustStore.passwordFile

Env. variable

LOG4J_TRANSPORT_SECURITY_TRUST_STORE_PASSWORD_FILE

Type

Path

Default value

null

The name of a file that contains the password for the trust store.

log4j.transportSecurity.trustStore.passwordEnvVar

Env. variable

LOG4J_TRANSPORT_SECURITY_TRUST_STORE_PASSWORD_ENV_VAR

Type

String

Default value

null

The name of the environment variable that contains password for the trust store.

log4j.transportSecurity.trustStore.type

Env. variable

LOG4J_TRANSPORT_SECURITY_TRUST_STORE_TYPE

Type

KeyStore type

Default value

Default Java KeyStore type

The type of trust store.

log4j.transportSecurity.trustStore.keyManagerFactory.algorithm

Env. variable

LOG4J_TRANSPORT_SECURITY_TRUST_STORE_KEY_MANAGER_FACTORY_ALGORITHM

Type

KeyManagerFactory type

Default value

Default Java KeyManagerFactory algorithm

Name of the KeyManagerFactory implementation to use for the trust store.

log4j.transportSecurity.verifyHostName

Env. variable

LOG4J_TRANSPORT_SECURITY_VERIFY_HOST_NAME

Type

boolean

Default value

false

If true enables verification of the name of the TLS server.

log4j.transportSecurity.keyStore.location

Env. variable

LOG4J_TRANSPORT_SECURITY_KEY_STORE_LOCATION

Type

Path or URI

Default value

see Default Java key store

The location of the private key store.

log4j.transportSecurity.keyStore.password

Env. variable

LOG4J_TRANSPORT_SECURITY_KEY_STORE_PASSWORD

Type

String

Default value

null

The password for the private key store.

log4j.transportSecurity.keyStore.passwordFile

Env. variable

LOG4J_TRANSPORT_SECURITY_KEY_STORE_PASSWORD_FILE

Type

Path

Default value

null

The name of a file that contains the password for the private key store.

log4j.transportSecurity.keyStore.passwordEnvVar

Env. variable

LOG4J_TRANSPORT_SECURITY_KEY_STORE_PASSWORD_ENV_VAR

Type

String

Default value

null

The name of the environment variable that contains the password for the private key store.

log4j.transportSecurity.keyStore.type

Env. variable

LOG4J_TRANSPORT_SECURITY_KEY_STORE_TYPE

Type

KeyStore type

Default value

Default Java KeyStore type

The type of private key store. KeyStore.

log4j.transportSecurity.keyStore.keyManagerFactory.algorithm

Env. variable

LOG4J_TRANSPORT_SECURITY_KEY_STORE_KEY_MANAGER_FACTORY_ALGORITHM

Type

KeyManagerFactory type

Default value

Default Java KeyManagerFactory algorithm

Name of the KeyManagerFactory implementation to use for the private key store. See KeyManagerFactory types.

Miscellaneous properties

log4j.configuration.clock

Env. variable

LOG4J_CONFIGURATION_CLOCK

Type

Class<? extends Clock> or predefined constant

Default value

SystemClock

Specifies the Clock implementation used to timestamp log events.

This must be the fully qualified class name of the implementation or one of these predefined constants:

SystemClock

uses the best available system clock as time source. See Clock.systemDefaultZone() for details.

SystemMillisClock

same as SystemClock, but truncates the result to a millisecond.

CachedClock

uses a separate thread to update the timestamp value. See CachedClock for details.

CoarseCachedClock

alternative implementation of CachedClock with a slightly lower precision. See JavaDoc for details.

log4j.configuration.usePreciseClock

Env. variable

LOG4J_CONFIGURATION_USE_PRECISE_CLOCK

Type

boolean

Default value

false

If set to true the SystemClock will use the best precision provided by the system. Otherwise, it will truncate the timestamp up to the milliseconds.

log4j.loader.ignoreTccl

Env. variable

LOG4J_LOADER_IGNORE_TCCL

Type

boolean

Default value

false

If true, classes are only loaded using the same classloader that loaded Log4j.

Otherwise, an attempt is made to load classes with the current thread’s context class loader before falling back to the default class loader.

log4j.configuration.reliabilityStrategy

Env. variable

LOG4J_CONFIGURATION_RELIABILITY_STRATEGY

Type

Class<? extends ReliabilityStrategy> or predefined constant

Default value

AwaitCompletion

Specifies the ReliabilityStrategy to adopt in order to prevent loss of log events during a reconfiguration.

The value must be the fully qualified class name of a ReliabilityStrategy implementation or one of these predefined constants:

AwaitCompletion

Counts the number of threads that have started to log an event but have not completed yet and waits for these threads to finish before stopping the appenders.

AwaitUnconditionally

Waits for a configured amount of time before stopping the appenders. See log4j.configuration.waitMillisBeforeStopOldConfig.

Locking

Uses read/write locks to prevent appenders from stopping while some threads are still logging events.

log4j.configuration.waitMillisBeforeStopOldConfig

Env. variable

LOG4J_CONFIGURATION_WAIT_MILLIS_BEFORE_STOP_OLD_CONFIG

Type

long

Default value

5000

Number of milliseconds to wait before stopping the old configuration if the AwaitUnconditionally reliability strategy is used. See log4j.configuration.reliabilityStrategy.

log4j.uuid.sequence

Env. variable

LOG4J_UUID_SEQUENCE

Type

long

Default value

0

Provides a long see to the UUID generator used by the %uuid pattern converter.

Can be used to assure uniqueness of UUIDs generated by multiple JVMs on the same machine.

Other components

Asynchronous Logger properties

Asynchronous loggers support the following additional properties:

log4j.async.logger.configExceptionHandler

Env. variable

LOG4J_ASYNC_LOGGER_CONFIG_EXCEPTION_HANDLER

Type

Class< ? extends AsyncLoggerConfigExceptionHandler>

Default value

AsyncLoggerConfigDefaultExceptionHandler

Fully qualified name of a class that implements the AsyncLoggerConfigExceptionHandler interface, which will be notified when an exception occurs while logging messages. The class needs to have a public zero-argument constructor.

The default exception handler will print a message and stack trace to the standard error output stream.

This configuration property is used, when Log4j uses a mix of sync and async loggers.

log4j.async.logger.exceptionHandler

Env. variable

LOG4J_ASYNC_LOGGER_EXCEPTION_HANDLER

Type

Class< ? extends AsyncLoggerExceptionHandler>

Default value

AsyncLoggerDefaultExceptionHandler

Fully qualified name of a class that implements the AsyncLoggerExceptionHandler interface, which will be notified when an exception occurs while logging messages. The class needs to have a public zero-argument constructor.

The default exception handler will print a message and stack trace to the standard error output stream.

This configuration property is used, when Log4j uses exclusively asynchronous loggers.

See Making all loggers asynchronous for more details.

log4j.async.logger.synchronizeEnqueueWhenQueueFull

Env. variable

LOG4J_ASYNC_LOGGER_SYNCHRONIZE_ENQUEUE_WHEN_QUEUE_FULL

Type

boolean

Default value

true

Synchronizes access to the LMAX Disruptor ring buffer for blocking enqueue operations when the queue is full. Users encountered excessive CPU utilization with LMAX Disruptor v3.4.2 when the application was logging more than the underlying appender could keep up with and the ring buffer became full, especially when the number of application threads vastly outnumbered the number of cores. CPU utilization is significantly reduced by restricting access to the enqueue operation. Setting this value to false may lead to very high CPU utilization when the async logging queue is full.

log4j.async.logger.ringBuffer.size

Env. variable

LOG4J_ASYNC_LOGGER_RING_BUFFER_SIZE

Type

int

Default value

256 × 1024

(GC-free mode: 4 × 1024)

Size (number of slots) in the RingBuffer used by the asynchronous logging subsystem. Make this value large enough to deal with bursts of activity. The minimum size is 128. The RingBuffer will be pre-allocated at first use and will never grow or shrink during the life of the system.

When the application is logging faster than the underlying appender can keep up with for a long enough time to fill up the queue, the behaviour is determined by the AsyncQueueFullPolicy.

log4j.async.logger.waitStrategy.type

Env. variable

LOG4J_ASYNC_LOGGER_WAIT_STRATEGY_TYPE

Type

predefined constant

Default value

Timeout

Specifies the WaitStrategy used by the LMAX Disruptor.

The value needs to be one of the predefined constants:

Block

a strategy that uses a lock and condition variable for the I/O thread waiting for log events. Block can be used when throughput and low-latency are not as important as CPU resource. Recommended for resource constrained/virtualised environments.

Timeout

a variation of the Block strategy that will periodically wake up from the lock condition await() call. This ensures that if a notification is missed somehow the consumer thread is not stuck but will recover with a small latency delay (see log4j.async.logger.waitStrategy.timeout)

Sleep

a strategy that initially spins, then uses a Thread.yield(), and eventually parks for the minimum number of nanos the OS and JVM will allow while the I/O thread is waiting for log events (see log4j.async.logger.waitStrategy.retries and log4j.async.logger.waitStrategy.sleepTimeNs). Sleep is a good compromise between performance and CPU resource. This strategy has very low impact on the application thread, in exchange for some additional latency for actually getting the message logged.

Yield

is a strategy that will use 100% CPU, but will give up the CPU if other threads require CPU resources.

log4j.async.logger.waitStrategy.retries

Env. variable

LOG4J_ASYNC_LOGGER_WAIT_STRATEGY_RETRIES

Type

int

Default value

200

Total number of spin cycles and Thread.yield() cycles of Sleep (see log4j.async.logger.waitStrategy.type).

log4j.async.logger.waitStrategy.sleepTimeNs

Env. variable

LOG4J_ASYNC_LOGGER_WAIT_STRATEGY_SLEEP_TIME_NS

Type

long

Default value

100

Sleep time in nanoseconds of Sleep wait strategy (see log4j.async.logger.waitStrategy.type).

log4j.async.logger.waitStrategy.timeout

Env. variable

LOG4J_ASYNC_LOGGER_WAIT_STRATEGY_TIMEOUT

Type

int

Default value

10

Timeout in milliseconds of Timeout wait strategy (see log4j.async.logger.waitStrategy.type).

JNDI support

Due to the inherent security problems of JNDI, its usage in Log4j is restricted to the java: protocol.

Moreover, each JNDI usage must be explicitly enabled by the user through the following configuration properties.

log4j.jndi.enableContextSelector

Env. variable

LOG4J_JNDI_ENABLE_CONTEXT_SELECTOR

Type

boolean

Default value

false

When true the JndiContextSelector is enabled for the java: protocol. See Web application for more details.

log4j.jndi.enableJdbc

Env. variable

LOG4J_JNDI_ENABLE_JDBC

Type

boolean

Default value

false

When true, a Log4j JDBC Appender can use JNDI to retrieve a DataSource using the java: protocol.

log4j.jndi.enableJms

Env. variable

LOG4J_JNDI_ENABLE_JMS

Type

boolean

Default value

false

When true, a Log4j JMS Appender can use JNDI to retrieve the necessary components using the java: protocol.

log4j.jndi.enableLookup

Env. variable

LOG4J_JNDI_ENABLE_LOOKUP

Type

boolean

Default value

false

When true, the Log4j JNDI Lookup can use the java: protocol.

JUL-to-Log4j API bridge properties

The JUL-to-Log4j API bridge provides the following configuration properties:

log4j.jul.levelConverter

Env. variable

LOG4J_JUL_LEVEL_CONVERTER

Type

Class<? extends LevelConverter>

Default value

org.apache.logging.jul.tolog4j.internal.DefaultLevelConverter

Fully qualified name of an alternative org.apache.logging.jul.tolog4j.spi.LevelConverter implementation.

Default level conversions
Java Level Log4j Level

OFF

OFF

SEVERE

ERROR

WARNING

WARN

INFO

INFO

CONFIG

custom CONFIG level with a numeric value of 450

FINE

DEBUG

FINER

TRACE

FINEST

custom FINEST level with a numeric value of 700

ALL

ALL

log4j.jul.loggerAdapter

Env. variable

LOG4J_JUL_LOGGER_ADAPTER

Type

Class<? extends AbstractLoggerAdapter>

Default value

org.apache.logging.jul.tolog4j.internal.ApiLoggerAdapter

Fully qualified class name of a custom org.apache.logging.jul.tolog4j.spi.AbstractLoggerAdapter implementation to use, which provides an implementation of the j.u.l.Logger mutator methods (e.g., Logger.setLevel()).

By default org.apache.logging.jul.tolog4j.internal.ApiLoggerAdapter is used and the mutator methods are disabled.

Script support

Script support can be configured using the following properties:

log4j.script.enableLanguages

Env. variable

LOG4J_SCRIPT_ENABLE_LANGUAGES

Type

Comma-separated list of ScriptEngine names

Default value

empty

The list of script languages that are allowed to execute.

The names specified must correspond to those returned by ScriptEngineFactory.getNames().

Property sources

The Log4j configuration properties sub-system is based on the PropertyEnvironment interface, which provides a type-safe access to configuration properties.

Two kinds of property environments are used by Log4j 3:

  • a single global environment resolves configuration properties that apply to the entire Log4j system.

  • logger context specific environments resolve configuration properties that apply to a single logger context only. If a property is not defined in a logger context specific environment, the corresponding value from the global environment is used.

Global environment

The global environment delegates property resolution to the Log4j 2 API PropertiesUtil service (see Log4j 2 API documentation).

Configuration properties can be declared in any of the property sources below, which use the standard naming convention:

log4j.propertyName

When resolving a configuration property, the first property source that contains a value is used.

Table 1. Global environment property sources
Name Naming Convention Module Description

SystemPropertiesPropertySource

standard

log4j-api

Resolves properties using Java System Properties.

EnvironmentPropertySource

custom

log4j-api

Resolves properties using environment variables.

Warning: The naming convention of this property source differs from the standard one. The property name is prefixed with LOG4J_, is in all caps and words are all separated by underscores.

PropertyFilePropertySource

standard

log4j-api

Resolves properties using all the resources named log4j2.component.properties found on the classpath. This property source should be used to change the default values of an application.

Additional property source classes can be added through:

  • the standard Java SE ServiceLoader mechanism,

  • programmatically using addPropertySource() and removePropertySource() static methods of PropertiesUtil class.

Logger context specific environment

The logger context specific environment resolve configuration properties that apply to a single logger context.

Configuration properties can be declared in any of the property sources below:

Table 2. Logger context specific property sources
Name Module Description

ContextualJavaPropsPropertySource

log4j-kit

Resolves properties using Java System Properties.

ContextualEnvironmentPropertySource

log4j-kit

Resolves properties using environment variables.

The ContextualJavaPropsPropertySource looks for Java system properties of the form:

log4j.contexts.<contextName>.propertyName

and its values take precedence over those from the ContextualEnvironmentPropertySource.

The ContextualEnvironmentPropertySource looks for environment variables named:

LOG4J_CONTEXTS_<contextName>_PROPERTY_NAME