Core infrastructure and basic components for the Logback logging framework, providing appenders, encoders, layouts, filters, and event processing pipeline
—
Comprehensive utility classes for file operations, date formatting, duration handling, size parsing, thread management, and testing support. These utilities provide essential infrastructure services used throughout the logback-core framework.
Utility class for representing and parsing file sizes with unit support.
/**
* Represents file sizes with unit parsing and formatting.
*/
public class FileSize {
/**
* Create FileSize with size in bytes.
* @param size size in bytes
*/
public FileSize(long size);
/**
* Set size from string with units (e.g., "10MB", "1GB").
* @param str size string with optional unit
*/
public void setSize(String str);
/**
* Get size in bytes.
* @return size in bytes
*/
public long getSize();
/**
* Get human-readable size string.
* @return formatted size (e.g., "10 MB")
*/
@Override
public String toString();
/**
* Parse size string to bytes.
* @param s size string (e.g., "100KB", "5MB", "2GB")
* @return size in bytes
*/
public static long valueOf(String s);
}File system utility methods for directory creation and resource handling.
/**
* File system utility methods.
*/
public class FileUtil {
/**
* Create missing parent directories for a file.
* @param file target file
* @return true if directories were created or already exist
*/
public static boolean createMissingParentDirectories(File file);
/**
* Load resource as string from classpath.
* @param classLoader class loader to use
* @param resourceName resource name
* @return resource content as string
*/
public static String resourceAsString(ClassLoader classLoader, String resourceName);
/**
* Check if parent directory creation is required.
* @param file target file
* @return true if parent directories need to be created
*/
public static boolean isParentDirectoryCreationRequired(File file);
/**
* Create missing target directories if necessary.
* @param file target file
* @return true if successful
*/
public static boolean createMissingTargetDirsIfNecessary(File file);
}Utility class for representing and parsing time durations with unit support.
/**
* Represents time durations with unit parsing and formatting.
*/
public class Duration {
/**
* Get duration in milliseconds.
* @return duration in milliseconds
*/
public long getMilliseconds();
/**
* Set duration in milliseconds.
* @param milliseconds duration in milliseconds
*/
public void setMilliseconds(long milliseconds);
/**
* Get human-readable duration string.
* @return formatted duration (e.g., "30 seconds")
*/
@Override
public String toString();
/**
* Parse duration string with units.
* @param s duration string (e.g., "30s", "5min", "2hours")
* @return Duration object
*/
public static Duration valueOf(String s);
}High-performance date formatter with caching for frequently used timestamps.
/**
* High-performance date formatter with timestamp caching.
*/
public class CachingDateFormatter {
/**
* Format timestamp with caching.
* @param now timestamp in milliseconds
* @return formatted date string
*/
public String format(long now);
/**
* Set time zone for formatting.
* @param tz time zone
*/
public void setTimeZone(TimeZone tz);
/**
* Get current time zone.
* @return time zone
*/
public TimeZone getTimeZone();
}Environment detection and capability checking utilities.
/**
* Environment detection and capability utilities.
*/
public class EnvUtil {
/**
* Check if Groovy is available on the classpath.
* @return true if Groovy is available
*/
public static boolean isGroovyAvailable();
/**
* Check if JANSI library is available for console colors.
* @return true if JANSI is available
*/
public static boolean isJansiAvailable();
/**
* Get JDK version number.
* @return JDK version (e.g., 8, 11, 17)
*/
public static int getJDKVersion();
/**
* Check if running on Windows.
* @return true if Windows OS
*/
public static boolean isWindows();
/**
* Check if running on Mac OS.
* @return true if Mac OS
*/
public static boolean isMac();
/**
* Check if running on Linux.
* @return true if Linux OS
*/
public static boolean isLinux();
}Context-related utility methods for hostname and collision detection.
/**
* Context-related utility methods.
*/
public class ContextUtil {
/**
* Get filename collision map for detecting conflicts.
* @param context target context
* @return map of filename collisions
*/
public static Map<String, String> getFilenameCollisionMap(Context context);
/**
* Get filename pattern collision map.
* @param context target context
* @return map of pattern collisions
*/
public static Map<String, FileNamePattern> getFilenamePatternCollisionMap(Context context);
/**
* Add hostname as a context property.
* @param context target context
*/
public static void addHostNameAsProperty(Context context);
}Thread interruption handling utilities.
/**
* Thread interruption utilities for proper cleanup.
*/
public class InterruptUtil {
/**
* Mask thread interrupt flag temporarily.
*/
public static void maskInterruptFlag();
/**
* Unmask thread interrupt flag.
*/
public static void unmaskInterruptFlag();
/**
* Check if current thread is interrupted.
* @return true if interrupted
*/
public static boolean isInterrupted();
}Rate limiting utility to prevent excessive method calls.
/**
* Rate limiting gate to prevent excessive method invocations.
*/
public class SimpleInvocationGate {
/**
* Check if invocation is too soon (rate limited).
* @param currentTime current timestamp
* @return true if invocation should be skipped
*/
public boolean isTooSoon(long currentTime);
/**
* Update timing mask if necessary.
* @param now current timestamp
*/
public void updateMaskIfNecessary(long now);
/**
* Set minimum interval between invocations.
* @param minDelayThreshold minimum delay in milliseconds
*/
public void setMinDelayThreshold(long minDelayThreshold);
}Configuration and object instantiation utilities.
/**
* Configuration and instantiation utilities.
*/
public class OptionHelper {
/**
* Check if string is empty or null.
* @param str string to check
* @return true if empty or null
*/
public static boolean isEmpty(String str);
/**
* Check if string is not empty.
* @param str string to check
* @return true if not empty and not null
*/
public static boolean isNotEmpty(String str);
/**
* Substitute variables in string using property container.
* @param val string with ${variable} placeholders
* @param pc property container for variable lookup
* @return string with variables substituted
*/
public static String substVars(String val, PropertyContainer pc);
/**
* Instantiate class by name with context injection.
* @param className fully qualified class name
* @param superClass expected superclass
* @param context context for dependency injection
* @return instantiated object
*/
public static Object instantiateByClassName(String className,
Class<?> superClass,
Context context);
/**
* Instantiate class with parameter.
* @param className class name to instantiate
* @param superClass expected superclass
* @param context context for injection
* @param type parameter type
* @param param parameter value
* @return instantiated object
*/
public static Object instantiateByClassNameAndParameter(String className,
Class<?> superClass,
Context context,
Class<?> type,
Object param);
}Testing-specific environment utilities.
/**
* Testing-specific environment utilities.
*/
public class EnvUtilForTests {
/**
* Set unit test mode flag.
* @param inUnitTestMode true if running in unit tests
*/
public static void setInUnitTestMode(boolean inUnitTestMode);
/**
* Check if running in unit test mode.
* @return true if in unit test mode
*/
public static boolean isInUnitTestMode();
}Random number generation utilities for testing.
/**
* Random number utilities for testing.
*/
public class RandomUtil {
/**
* Get a positive random integer.
* @return positive random integer
*/
public static int getPositiveInt();
/**
* Generate random string of specified length.
* @param length string length
* @return random string
*/
public static String randomString(int length);
/**
* Get random port number in valid range.
* @return random port number
*/
public static int getRandomServerPort();
}Output stream that writes to multiple targets simultaneously.
/**
* Output stream that writes to multiple targets.
*/
public class TeeOutputStream extends OutputStream {
/**
* Create tee stream with two outputs.
* @param o1 first output stream
* @param o2 second output stream
*/
public TeeOutputStream(OutputStream o1, OutputStream o2);
@Override
public void write(int b) throws IOException;
@Override
public void write(byte[] b) throws IOException;
@Override
public void write(byte[] b, int off, int len) throws IOException;
@Override
public void flush() throws IOException;
@Override
public void close() throws IOException;
}Generic cyclic buffer implementation for fixed-size collections.
/**
* Generic cyclic buffer with fixed size.
*/
public class CyclicBuffer<E> {
/**
* Create cyclic buffer with specified capacity.
* @param capacity maximum number of elements
*/
public CyclicBuffer(int capacity);
/**
* Add element (overwrites oldest if full).
* @param e element to add
*/
public void add(E e);
/**
* Get element at index.
* @param index element index
* @return element at index
*/
public E get(int index);
/**
* Get current number of elements.
* @return current size
*/
public int length();
/**
* Get maximum capacity.
* @return maximum size
*/
public int getMaxSize();
/**
* Resize buffer capacity.
* @param newSize new capacity
*/
public void resize(int newSize);
/**
* Clear all elements.
*/
public void clear();
}Utility for tracking components with timeout-based cleanup.
/**
* Component tracker with timeout-based cleanup.
*/
public class ComponentTracker<C> {
/**
* Find component by key.
* @param key component key
* @return component or null if not found
*/
public C find(String key);
/**
* Get existing component or create new one.
* @param key component key
* @param timestamp current timestamp
* @return existing or new component
*/
public C getOrCreate(String key, long timestamp);
/**
* Remove stale components based on timestamp.
* @param now current timestamp
*/
public void removeStaleComponents(long now);
/**
* Set maximum idle time before component removal.
* @param maxIdleTime idle time in milliseconds
*/
public void setMaxIdleTime(long maxIdleTime);
/**
* Get maximum idle time.
* @return idle time in milliseconds
*/
public long getMaxIdleTime();
/**
* Get all tracked component keys.
* @return set of component keys
*/
public Set<String> allKeys();
}import ch.qos.logback.core.util.FileSize;
// Parse file sizes from strings
FileSize size1 = new FileSize(FileSize.valueOf("100MB"));
FileSize size2 = new FileSize(FileSize.valueOf("1.5GB"));
FileSize size3 = new FileSize(FileSize.valueOf("512KB"));
// Create from bytes
FileSize size4 = new FileSize(1024 * 1024 * 50); // 50MB
// Format for display
System.out.println(size1.toString()); // "100 MB"
System.out.println(size2.toString()); // "1.5 GB"
// Use in configuration
FileAppender<?> appender = new FileAppender<>();
appender.setBufferSize(new FileSize(8192)); // 8KB bufferimport ch.qos.logback.core.util.Duration;
// Parse duration strings
Duration timeout = Duration.valueOf("30 seconds");
Duration delay = Duration.valueOf("5 minutes");
Duration retention = Duration.valueOf("7 days");
// Create from milliseconds
Duration custom = new Duration();
custom.setMilliseconds(15000); // 15 seconds
// Use with appenders
SocketAppender socketAppender = new SocketAppender();
socketAppender.setReconnectionDelay(Duration.valueOf("10s"));import ch.qos.logback.core.util.EnvUtil;
// Check environment capabilities
if (EnvUtil.isJansiAvailable()) {
// Enable console colors
enableColorOutput();
}
if (EnvUtil.isGroovyAvailable()) {
// Enable Groovy-based evaluators
setupGroovyEvaluators();
}
// Platform-specific configuration
if (EnvUtil.isWindows()) {
logFile = "C:\\logs\\application.log";
} else {
logFile = "/var/log/application.log";
}
// JDK version specific features
int jdkVersion = EnvUtil.getJDKVersion();
if (jdkVersion >= 11) {
// Use modern APIs
}import ch.qos.logback.core.util.OptionHelper;
// Substitute variables in configuration strings
String pattern = "${LOG_DIR}/app-${HOSTNAME}.log";
String resolved = OptionHelper.substVars(pattern, context);
// Result: "/var/log/app-server01.log"
// Check string values
if (OptionHelper.isEmpty(configValue)) {
// Use default
configValue = defaultValue;
}import ch.qos.logback.core.util.OptionHelper;
// Dynamically instantiate components
String className = "com.example.CustomAppender";
Object instance = OptionHelper.instantiateByClassName(
className,
Appender.class,
context
);
if (instance instanceof Appender) {
Appender<?> appender = (Appender<?>) instance;
// Configure and use appender
}import ch.qos.logback.core.util.SimpleInvocationGate;
public class RateLimitedLogger {
private final SimpleInvocationGate gate = new SimpleInvocationGate();
public RateLimitedLogger() {
gate.setMinDelayThreshold(1000); // Maximum once per second
}
public void logExpensiveOperation(String message) {
long now = System.currentTimeMillis();
if (!gate.isTooSoon(now)) {
// Perform expensive logging operation
performComplexLogging(message);
}
// Otherwise skip this log event
}
}import ch.qos.logback.core.util.CyclicBuffer;
public class RecentEventsBuffer<E> {
private final CyclicBuffer<E> buffer;
public RecentEventsBuffer(int capacity) {
this.buffer = new CyclicBuffer<>(capacity);
}
public void addEvent(E event) {
buffer.add(event);
}
public List<E> getRecentEvents() {
List<E> events = new ArrayList<>();
for (int i = 0; i < buffer.length(); i++) {
events.add(buffer.get(i));
}
return events;
}
public void clearEvents() {
buffer.clear();
}
}import ch.qos.logback.core.util.ComponentTracker;
public class AppenderManager {
private final ComponentTracker<Appender<?>> tracker = new ComponentTracker<>();
public AppenderManager() {
tracker.setMaxIdleTime(30 * 60 * 1000); // 30 minutes
}
public Appender<?> getAppender(String name) {
long now = System.currentTimeMillis();
// Clean up stale appenders first
tracker.removeStaleComponents(now);
// Get or create appender
return tracker.getOrCreate(name, now);
}
public void shutdown() {
// Stop all tracked appenders
for (String key : tracker.allKeys()) {
Appender<?> appender = tracker.find(key);
if (appender != null && appender.isStarted()) {
appender.stop();
}
}
}
}import ch.qos.logback.core.util.TeeOutputStream;
public class TestOutputCapture {
public void captureOutput() throws IOException {
ByteArrayOutputStream captured = new ByteArrayOutputStream();
TeeOutputStream tee = new TeeOutputStream(System.out, captured);
// Redirect output to both console and capture buffer
PrintStream originalOut = System.out;
System.setOut(new PrintStream(tee));
try {
// Run code that produces output
System.out.println("This goes to both console and buffer");
// Verify captured output
String output = captured.toString();
assert output.contains("This goes to both");
} finally {
System.setOut(originalOut);
tee.close();
}
}
}These utilities provide the foundation for robust, cross-platform logging infrastructure with proper resource management and error handling.
Install with Tessl CLI
npx tessl i tessl/maven-ch-qos-logback--logback-core