A versatile, industrial-grade, and reference implementation of the Log4j API with rich components for various logging use cases.
—
Log4j Core provides comprehensive configuration management supporting multiple file formats (XML, JSON, YAML, Properties) and programmatic configuration through a fluent builder API. The configuration system manages loggers, appenders, layouts, filters, and global settings.
Base interface that all configuration implementations must implement.
/**
* Core configuration interface managing logging components
*/
public interface Configuration {
/**
* Get configuration name
* @return Configuration name
*/
String getName();
/**
* Get logger configuration by name
* @param name Logger name
* @return LoggerConfig instance
*/
LoggerConfig getLoggerConfig(String name);
/**
* Get appender by name
* @param name Appender name
* @return Appender instance with generic type
*/
<T extends Appender> T getAppender(String name);
/**
* Get all appenders
* @return Map of appender names to instances
*/
Map<String, Appender> getAppenders();
/**
* Get all logger configurations
* @return Map of logger names to configurations
*/
Map<String, LoggerConfig> getLoggers();
/**
* Get root logger configuration
* @return Root LoggerConfig instance
*/
LoggerConfig getRootLogger();
/**
* Get configuration source
* @return ConfigurationSource instance
*/
ConfigurationSource getConfigurationSource();
/**
* Get string substitution handler
* @return StrSubstitutor for variable replacement
*/
StrSubstitutor getStrSubstitutor();
/**
* Get plugin packages list
* @return List of plugin package names
*/
List<String> getPluginPackages();
/**
* Get configuration properties
* @return Map of property names to values
*/
Map<String, String> getProperties();
/**
* Initialize the configuration
*/
void initialize();
/**
* Start the configuration
*/
void start();
/**
* Stop the configuration with timeout
* @param timeout Maximum wait time
* @param timeUnit Time unit for timeout
* @return true if stopped within timeout
*/
boolean stop(long timeout, TimeUnit timeUnit);
/**
* Get configuration state
* @return Current lifecycle state
*/
LifeCycle.State getState();
/**
* Check if configuration is started
* @return true if started
*/
boolean isStarted();
/**
* Check if configuration is stopped
* @return true if stopped
*/
boolean isStopped();
}Factory for creating and managing configurations from various sources.
/**
* Get the configuration factory instance
* @return ConfigurationFactory singleton
*/
public static ConfigurationFactory getInstance();
/**
* Create configuration from source
* @param loggerContext Logger context
* @param name Configuration name
* @param configLocation Configuration location URI
* @return Configuration instance
*/
public abstract Configuration getConfiguration(LoggerContext loggerContext, String name, URI configLocation);
/**
* Get supported configuration file types
* @return Array of supported file extensions
*/
public abstract String[] getSupportedTypes();
/**
* Create configuration from configuration source
* @param loggerContext Logger context
* @param source Configuration source
* @return Configuration instance
*/
public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source);Usage Examples:
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.LoggerContext;
import java.net.URI;
// Get factory and create configuration
ConfigurationFactory factory = ConfigurationFactory.getInstance();
LoggerContext context = LoggerContext.getContext(false);
// Load configuration from file
URI configLocation = new URI("file:///path/to/log4j2.xml");
Configuration config = factory.getConfiguration(context, "MyConfig", configLocation);
// Check supported types
String[] supportedTypes = factory.getSupportedTypes();
// Returns: [".xml", ".json", ".yaml", ".yml", ".properties"]Static utility class for common configuration operations.
/**
* Initialize logger context with configuration
* @param name Context name
* @param loader ClassLoader to use
* @param configLocation Configuration file location
* @return Initialized LoggerContext
*/
public static LoggerContext initialize(String name, ClassLoader loader, String configLocation);
/**
* Initialize with configuration and external context
* @param name Context name
* @param loader ClassLoader to use
* @param configLocation Configuration file location
* @param externalContext External context object
* @return Initialized LoggerContext
*/
public static LoggerContext initialize(String name, ClassLoader loader, String configLocation, Object externalContext);
/**
* Shutdown logger context
* @param context LoggerContext to shutdown
*/
public static void shutdown(LoggerContext context);
/**
* Set log level for specific logger
* @param loggerName Logger name
* @param level Level to set
*/
public static void setLevel(String loggerName, Level level);
/**
* Set root logger level
* @param level Level to set for root logger
*/
public static void setRootLevel(Level level);
/**
* Set level for logger and all descendant loggers
* @param loggerName Logger name
* @param level Level to set
*/
public static void setAllLevels(String loggerName, Level level);
/**
* Reconfigure with new configuration file
* @param configLocation New configuration file location
* @return Updated LoggerContext
*/
public static LoggerContext reconfigure(String configLocation);Usage Examples:
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.Level;
// Initialize with custom configuration
LoggerContext context = Configurator.initialize(
"MyApplication",
MyApp.class.getClassLoader(),
"log4j2-production.xml"
);
// Set various logger levels
Configurator.setRootLevel(Level.INFO);
Configurator.setLevel("com.example", Level.DEBUG);
Configurator.setLevel("com.example.security", Level.TRACE);
Configurator.setAllLevels("com.example.noisy", Level.WARN);
// Reconfigure at runtime
LoggerContext newContext = Configurator.reconfigure("log4j2-debug.xml");
// Shutdown when application exits
Configurator.shutdown(context);Configuration class for individual loggers within the system.
/**
* LoggerConfig manages configuration for individual loggers
*/
public class LoggerConfig {
/**
* Add appender to this logger config
* @param appender Appender to add
* @param level Minimum level for this appender
* @param filter Filter for this appender
*/
public void addAppender(Appender appender, Level level, Filter filter);
/**
* Remove appender by name
* @param name Appender name to remove
*/
public void removeAppender(String name);
/**
* Get all appenders for this logger
* @return Map of appender names to instances
*/
public Map<String, Appender> getAppenders();
/**
* Get logger level
* @return Current Level
*/
public Level getLevel();
/**
* Set logger level
* @param level Level to set
*/
public void setLevel(Level level);
/**
* Check if logger is additive
* @return true if additive
*/
public boolean isAdditive();
/**
* Set logger additivity
* @param additive Additivity flag
*/
public void setAdditive(boolean additive);
/**
* Get logger name
* @return Logger name
*/
public String getName();
/**
* Get parent logger config
* @return Parent LoggerConfig or null
*/
public LoggerConfig getParent();
}Usage Examples:
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.appender.FileAppender;
// Get logger configuration
Configuration config = context.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig("com.example.MyClass");
// Configure logger
loggerConfig.setLevel(Level.DEBUG);
loggerConfig.setAdditive(false);
// Add appender to specific logger
FileAppender fileAppender = FileAppender.newBuilder()
.setName("MyClassFile")
.withFileName("myclass.log")
.build();
loggerConfig.addAppender(fileAppender, Level.INFO, null);
// Remove appender
loggerConfig.removeAppender("MyClassFile");Programmatic configuration through fluent builder interface.
/**
* Fluent API for building configurations programmatically
* @param <T> Built configuration type
*/
public interface ConfigurationBuilder<T extends BuiltConfiguration> {
/**
* Set plugin packages
* @param packages Comma-separated package names
* @return ConfigurationBuilder instance
*/
ConfigurationBuilder<T> setPackages(String packages);
/**
* Set configuration name
* @param name Configuration name
* @return ConfigurationBuilder instance
*/
ConfigurationBuilder<T> setConfigurationName(String name);
/**
* Set status level for internal Log4j logging
* @param level Status level
* @return ConfigurationBuilder instance
*/
ConfigurationBuilder<T> setStatusLevel(Level level);
/**
* Create new appender component
* @param name Appender name
* @param type Appender type
* @return AppenderComponentBuilder instance
*/
AppenderComponentBuilder newAppender(String name, String type);
/**
* Create new layout component
* @param type Layout type
* @return LayoutComponentBuilder instance
*/
LayoutComponentBuilder newLayout(String type);
/**
* Create new filter component
* @param type Filter type
* @return FilterComponentBuilder instance
*/
FilterComponentBuilder newFilter(String type);
/**
* Create new logger component
* @param name Logger name
* @param level Logger level
* @return LoggerComponentBuilder instance
*/
LoggerComponentBuilder newLogger(String name, Level level);
/**
* Create new root logger component
* @param level Root logger level
* @return RootLoggerComponentBuilder instance
*/
RootLoggerComponentBuilder newRootLogger(Level level);
/**
* Build the configuration
* @return Built configuration instance
*/
T build();
}/**
* Factory for creating configuration builders
*/
public class ConfigurationBuilderFactory {
/**
* Create new configuration builder
* @return ConfigurationBuilder instance
*/
public static ConfigurationBuilder<BuiltConfiguration> newConfigurationBuilder();
}/**
* Builder for appender components
*/
public interface AppenderComponentBuilder extends ComponentBuilder<AppenderComponentBuilder> {
AppenderComponentBuilder add(LayoutComponentBuilder layout);
AppenderComponentBuilder add(FilterComponentBuilder filter);
AppenderComponentBuilder addAttribute(String key, String value);
}
/**
* Builder for layout components
*/
public interface LayoutComponentBuilder extends ComponentBuilder<LayoutComponentBuilder> {
LayoutComponentBuilder addAttribute(String key, String value);
}
/**
* Builder for filter components
*/
public interface FilterComponentBuilder extends ComponentBuilder<FilterComponentBuilder> {
FilterComponentBuilder addAttribute(String key, String value);
}
/**
* Builder for logger components
*/
public interface LoggerComponentBuilder extends ComponentBuilder<LoggerComponentBuilder> {
LoggerComponentBuilder add(AppenderRef ref);
LoggerComponentBuilder add(FilterComponentBuilder filter);
LoggerComponentBuilder addAttribute(String key, String value);
}
/**
* Builder for root logger components
*/
public interface RootLoggerComponentBuilder extends ComponentBuilder<RootLoggerComponentBuilder> {
RootLoggerComponentBuilder add(AppenderRef ref);
RootLoggerComponentBuilder add(FilterComponentBuilder filter);
}Usage Examples:
import org.apache.logging.log4j.core.config.builder.api.*;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
// Create configuration programmatically
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
// Set global properties
builder.setConfigurationName("ProgrammaticConfig")
.setStatusLevel(Level.WARN)
.setPackages("com.example.plugins");
// Create console appender
AppenderComponentBuilder consoleAppender = builder.newAppender("Console", "CONSOLE")
.addAttribute("target", "SYSTEM_OUT");
// Create pattern layout
LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout")
.addAttribute("pattern", "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n");
consoleAppender.add(layoutBuilder);
// Create file appender
AppenderComponentBuilder fileAppender = builder.newAppender("File", "File")
.addAttribute("fileName", "application.log")
.addAttribute("append", "true")
.add(layoutBuilder);
// Create root logger
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.INFO)
.add(builder.newAppenderRef("Console"))
.add(builder.newAppenderRef("File"));
// Create specific logger
LoggerComponentBuilder logger = builder.newLogger("com.example", Level.DEBUG)
.add(builder.newAppenderRef("File"))
.addAttribute("additivity", "false");
// Add components to configuration
builder.add(consoleAppender);
builder.add(fileAppender);
builder.add(rootLogger);
builder.add(logger);
// Build and apply configuration
BuiltConfiguration config = builder.build();
LoggerContext context = LoggerContext.getContext(false);
context.start(config);/**
* Reference to an appender for use in logger configurations
*/
public class AppenderRef {
/**
* Create appender reference
* @param ref Appender name to reference
* @param level Minimum level for this reference
* @param filter Filter for this reference
* @return AppenderRef instance
*/
public static AppenderRef createAppenderRef(String ref, Level level, Filter filter);
/**
* Get referenced appender name
* @return Appender name
*/
public String getRef();
/**
* Get level for this reference
* @return Level or null
*/
public Level getLevel();
/**
* Get filter for this reference
* @return Filter or null
*/
public Filter getFilter();
}<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<File name="File" fileName="application.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</File>
</Appenders>
<Loggers>
<Logger name="com.example" level="DEBUG" additivity="false">
<AppenderRef ref="File"/>
</Logger>
<Root level="INFO">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>{
"Configuration": {
"status": "WARN",
"Appenders": {
"Console": {
"name": "Console",
"target": "SYSTEM_OUT",
"PatternLayout": {
"pattern": "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"
}
}
},
"Loggers": {
"Root": {
"level": "INFO",
"AppenderRef": { "ref": "Console" }
}
}
}
}Configuration:
status: WARN
Appenders:
Console:
name: Console
target: SYSTEM_OUT
PatternLayout:
pattern: "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"
Loggers:
Root:
level: INFO
AppenderRef:
ref: ConsoleInstall with Tessl CLI
npx tessl i tessl/maven-org-apache-logging-log4j--log4j-core