Core infrastructure and basic components for the Logback logging framework, providing appenders, encoders, layouts, filters, and event processing pipeline
—
Advanced file management with time-based and size-based rolling, compression support, and cleanup policies for log file rotation and archival. Rolling policies enable automatic log file management to prevent disk space issues and maintain organized log archives.
Core interface defining how and when log files are rolled over.
/**
* Interface for defining file rollover behavior.
* Rolling policies determine when and how log files are rotated.
*/
public interface RollingPolicy extends LifeCycle {
/**
* Perform the rollover operation.
* @throws RolloverFailure if rollover cannot be completed
*/
void rollover() throws RolloverFailure;
/**
* Get the name of the currently active log file.
* @return active file name
*/
String getActiveFileName();
/**
* Get the compression mode for archived files.
* @return compression mode (NONE, GZ, ZIP)
*/
CompressionMode getCompressionMode();
/**
* Set the parent file appender.
* @param appender the file appender using this policy
*/
void setParent(FileAppender<?> appender);
}Interface for determining when rollover should occur.
/**
* Interface for determining when file rollover should be triggered.
*/
public interface TriggeringPolicy<E> extends LifeCycle {
/**
* Check if the given event should trigger a rollover.
* @param activeFile the current active log file
* @param event the current event being logged
* @return true if rollover should occur
*/
boolean isTriggeringEvent(File activeFile, E event);
}File appender with rolling capability that coordinates rolling and triggering policies.
/**
* File appender with automatic rolling support.
* Combines RollingPolicy and TriggeringPolicy for complete file management.
*/
public class RollingFileAppender<E> extends FileAppender<E> {
private RollingPolicy rollingPolicy;
private TriggeringPolicy<E> triggeringPolicy;
/**
* Set the rolling policy.
* @param policy the rolling policy to use
*/
public void setRollingPolicy(RollingPolicy policy);
/**
* Get the current rolling policy.
* @return the rolling policy
*/
public RollingPolicy getRollingPolicy();
/**
* Set the triggering policy.
* @param policy the triggering policy to use
*/
public void setTriggeringPolicy(TriggeringPolicy<E> policy);
/**
* Get the current triggering policy.
* @return the triggering policy
*/
public TriggeringPolicy<E> getTriggeringPolicy();
/**
* Force an immediate rollover.
* @throws RolloverFailure if rollover fails
*/
public void rollover() throws RolloverFailure;
@Override
protected void append(E eventObject);
@Override
public void start();
@Override
public void stop();
}Base implementation providing common rolling policy functionality.
/**
* Base class for rolling policies with common configuration options.
*/
public abstract class RollingPolicyBase extends ContextAwareBase implements RollingPolicy {
protected FileAppender<?> parent;
protected String fileNamePattern;
protected int maxHistory = 0;
protected FileSize totalSizeCap = new FileSize(0);
protected boolean cleanHistoryOnStart = false;
/**
* Set the file name pattern for rolled files.
* Pattern supports date/time tokens and integer tokens.
* @param fnp file name pattern (e.g., "app.%d{yyyy-MM-dd}.log")
*/
public void setFileNamePattern(String fnp);
/**
* Get the file name pattern.
* @return file name pattern
*/
public String getFileNamePattern();
/**
* Set maximum number of archive files to keep.
* @param maxHistory maximum history count (0 = no limit)
*/
public void setMaxHistory(int maxHistory);
/**
* Get the maximum history count.
* @return maximum history count
*/
public int getMaxHistory();
/**
* Set total size cap for all archive files.
* @param totalSizeCap maximum total size of archives
*/
public void setTotalSizeCap(FileSize totalSizeCap);
/**
* Get the total size cap.
* @return total size cap
*/
public FileSize getTotalSizeCap();
/**
* Enable cleaning old archives on startup.
* @param cleanHistoryOnStart true to clean on start
*/
public void setCleanHistoryOnStart(boolean cleanHistoryOnStart);
/**
* Check if clean history on start is enabled.
* @return true if enabled
*/
public boolean isCleanHistoryOnStart();
/**
* Set the parent file appender.
* @param appender the parent appender
*/
public void setParent(FileAppender<?> appender);
/**
* Get the parent file appender.
* @return the parent appender
*/
public FileAppender<?> getParent();
}Time-based rolling policy supporting date/time patterns and size-based splitting.
/**
* Rolling policy based on time patterns with optional size-based splitting.
* Supports daily, hourly, or custom time-based rollover with compression.
*/
public class TimeBasedRollingPolicy<E> extends RollingPolicyBase
implements TriggeringPolicy<E> {
private FileSize maxFileSize;
/**
* Set maximum file size for size-based splitting within time periods.
* @param maxFileSize maximum size before splitting (e.g., "10MB")
*/
public void setMaxFileSize(FileSize maxFileSize);
/**
* Get the maximum file size.
* @return maximum file size
*/
public FileSize getMaxFileSize();
/**
* Perform time-based rollover.
* Creates archive file based on time pattern and starts new active file.
*/
@Override
public void rollover() throws RolloverFailure;
/**
* Check if rollover should be triggered based on time or size.
* @param activeFile current active file
* @param event current event
* @return true if rollover needed
*/
@Override
public boolean isTriggeringEvent(File activeFile, E event);
/**
* Get compression mode based on file name pattern.
* @return NONE, GZ, or ZIP based on pattern extension
*/
@Override
public CompressionMode getCompressionMode();
@Override
public String getActiveFileName();
@Override
public void start();
@Override
public void stop();
}Combined size and time-based rolling with multiple files per time period.
/**
* Rolling policy combining time-based and size-based strategies.
* Creates multiple files per time period when size limits are exceeded.
*/
public class SizeAndTimeBasedRollingPolicy<E> extends TimeBasedRollingPolicy<E> {
/**
* Inherits all methods from TimeBasedRollingPolicy.
* Adds intelligence to create multiple files per time period based on size.
*/
@Override
public void rollover() throws RolloverFailure;
@Override
public boolean isTriggeringEvent(File activeFile, E event);
}Rolling policy that maintains a fixed window of numbered log files.
/**
* Rolling policy that maintains a fixed number of numbered backup files.
* Files are renamed in sequence (app.1.log, app.2.log, etc.).
*/
public class FixedWindowRollingPolicy extends RollingPolicyBase {
private int minIndex = 1;
private int maxIndex = 7;
/**
* Set the minimum index for backup files.
* @param minIndex minimum index (usually 1)
*/
public void setMinIndex(int minIndex);
/**
* Get the minimum index.
* @return minimum index
*/
public int getMinIndex();
/**
* Set the maximum index for backup files.
* @param maxIndex maximum index (determines number of backup files)
*/
public void setMaxIndex(int maxIndex);
/**
* Get the maximum index.
* @return maximum index
*/
public int getMaxIndex();
/**
* Perform fixed window rollover.
* Renames existing files and compresses oldest if needed.
*/
@Override
public void rollover() throws RolloverFailure;
@Override
public String getActiveFileName();
@Override
public CompressionMode getCompressionMode();
@Override
public void start();
}Triggering policy that rolls over when file size exceeds a threshold.
/**
* Triggering policy based on file size.
* Triggers rollover when active file exceeds specified size.
*/
public class SizeBasedTriggeringPolicy<E> extends TriggeringPolicyBase<E> {
private FileSize maxFileSize = new FileSize(10 * 1024 * 1024); // 10MB default
/**
* Set the maximum file size before triggering rollover.
* @param maxFileSize maximum size (e.g., "10MB", "1GB")
*/
public void setMaxFileSize(FileSize maxFileSize);
/**
* Get the maximum file size.
* @return maximum file size
*/
public FileSize getMaxFileSize();
/**
* Check if file size exceeds threshold.
* @param activeFile current active file
* @param event current event (not used for size-based triggering)
* @return true if file size exceeds maxFileSize
*/
@Override
public boolean isTriggeringEvent(File activeFile, E event);
@Override
public void start();
}Base class for triggering policies.
/**
* Base class for triggering policies with lifecycle support.
*/
public abstract class TriggeringPolicyBase<E> extends ContextAwareBase
implements TriggeringPolicy<E> {
private boolean started = false;
/**
* Start the triggering policy.
*/
public void start();
/**
* Stop the triggering policy.
*/
public void stop();
/**
* Check if the policy is started.
* @return true if started
*/
public boolean isStarted();
}Enumeration of supported compression types.
/**
* Supported compression modes for archived log files.
*/
public enum CompressionMode {
/**
* No compression.
*/
NONE,
/**
* Gzip compression (.gz extension).
*/
GZ,
/**
* ZIP compression (.zip extension).
*/
ZIP
}Helper class for parsing and working with file name patterns.
/**
* Utility for working with file name patterns containing date/time tokens.
*/
public class FileNamePattern {
/**
* Convert object to string using the pattern.
* @param o object to convert (usually Date or Integer)
* @return formatted string
*/
public String convert(Object o);
/**
* Convert pattern to regular expression.
* @return regex pattern for matching files
*/
public String toRegex();
/**
* Check if pattern contains integer token converter.
* @return true if pattern has integer tokens
*/
public boolean hasIntegerTokenConverter();
/**
* Get the integer token converter.
* @return integer token converter, or null
*/
public IntegerTokenConverter getIntegerTokenConverter();
/**
* Parse date from filename using pattern.
* @param file file to parse
* @return parsed date, or null if no match
*/
public Date parseFilename(File file);
}Exception thrown when rollover operations fail.
/**
* Exception thrown when rollover operations cannot be completed.
*/
public class RolloverFailure extends Exception {
/**
* Create exception with message.
* @param msg error message
*/
public RolloverFailure(String msg);
/**
* Create exception with message and cause.
* @param msg error message
* @param cause underlying cause
*/
public RolloverFailure(String msg, Throwable cause);
}import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
// Create rolling file appender
RollingFileAppender<Object> appender = new RollingFileAppender<>();
appender.setContext(context);
appender.setFile("application.log");
// Configure time-based rolling policy
TimeBasedRollingPolicy<Object> rollingPolicy = new TimeBasedRollingPolicy<>();
rollingPolicy.setContext(context);
rollingPolicy.setParent(appender);
rollingPolicy.setFileNamePattern("application.%d{yyyy-MM-dd}.log");
rollingPolicy.setMaxHistory(30); // Keep 30 days
rollingPolicy.setCleanHistoryOnStart(true);
rollingPolicy.start();
// Set policies on appender
appender.setRollingPolicy(rollingPolicy);
appender.setTriggeringPolicy(rollingPolicy); // TimeBasedRollingPolicy implements both
appender.setEncoder(encoder);
appender.start();import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy;
import ch.qos.logback.core.util.FileSize;
RollingFileAppender<Object> appender = new RollingFileAppender<>();
appender.setContext(context);
appender.setFile("application.log");
// Combined size and time-based policy
SizeAndTimeBasedRollingPolicy<Object> policy = new SizeAndTimeBasedRollingPolicy<>();
policy.setContext(context);
policy.setParent(appender);
policy.setFileNamePattern("application.%d{yyyy-MM-dd}.%i.log.gz"); // .gz for compression
policy.setMaxFileSize(new FileSize(100 * 1024 * 1024)); // 100MB per file
policy.setMaxHistory(60); // Keep 60 days
policy.setTotalSizeCap(new FileSize(20 * 1024 * 1024 * 1024L)); // 20GB total
policy.start();
appender.setRollingPolicy(policy);
appender.setTriggeringPolicy(policy);
appender.setEncoder(encoder);
appender.start();import ch.qos.logback.core.rolling.FixedWindowRollingPolicy;
import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
RollingFileAppender<Object> appender = new RollingFileAppender<>();
appender.setContext(context);
appender.setFile("application.log");
// Fixed window rolling policy
FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy();
rollingPolicy.setContext(context);
rollingPolicy.setParent(appender);
rollingPolicy.setFileNamePattern("application.%i.log.zip"); // ZIP compression
rollingPolicy.setMinIndex(1);
rollingPolicy.setMaxIndex(10); // Keep 10 backup files
rollingPolicy.start();
// Size-based triggering policy
SizeBasedTriggeringPolicy<Object> triggeringPolicy = new SizeBasedTriggeringPolicy<>();
triggeringPolicy.setContext(context);
triggeringPolicy.setMaxFileSize(new FileSize(50 * 1024 * 1024)); // 50MB
triggeringPolicy.start();
appender.setRollingPolicy(rollingPolicy);
appender.setTriggeringPolicy(triggeringPolicy);
appender.setEncoder(encoder);
appender.start();TimeBasedRollingPolicy<Object> hourlyPolicy = new TimeBasedRollingPolicy<>();
hourlyPolicy.setContext(context);
hourlyPolicy.setParent(appender);
hourlyPolicy.setFileNamePattern("application.%d{yyyy-MM-dd-HH}.log");
hourlyPolicy.setMaxFileSize(new FileSize(10 * 1024 * 1024)); // 10MB max per hour
hourlyPolicy.setMaxHistory(24 * 7); // Keep one week (24 hours × 7 days)
hourlyPolicy.start();import ch.qos.logback.core.rolling.RollingPolicyBase;
public class CustomRollingPolicy extends RollingPolicyBase {
private String customPattern;
@Override
public void rollover() throws RolloverFailure {
// Custom rollover logic
String activeFile = getActiveFileName();
String archiveFile = generateArchiveFileName();
try {
// Rename current file
Files.move(Paths.get(activeFile), Paths.get(archiveFile));
// Optionally compress
if (getCompressionMode() != CompressionMode.NONE) {
compressFile(archiveFile);
}
// Clean old files if needed
cleanupOldFiles();
} catch (IOException e) {
throw new RolloverFailure("Failed to rollover", e);
}
}
@Override
public String getActiveFileName() {
return parent.getFile();
}
@Override
public CompressionMode getCompressionMode() {
if (fileNamePattern != null && fileNamePattern.endsWith(".gz")) {
return CompressionMode.GZ;
} else if (fileNamePattern != null && fileNamePattern.endsWith(".zip")) {
return CompressionMode.ZIP;
}
return CompressionMode.NONE;
}
private String generateArchiveFileName() {
// Custom archive file name generation
return String.format("app-%d.log", System.currentTimeMillis());
}
private void compressFile(String fileName) throws IOException {
// Custom compression logic
}
private void cleanupOldFiles() {
// Custom cleanup logic based on maxHistory
}
public void setCustomPattern(String customPattern) {
this.customPattern = customPattern;
}
}File name patterns support various tokens:
%d{yyyy-MM-dd} - Date format (daily rolling)%d{yyyy-MM-dd-HH} - Hour format (hourly rolling)%d{yyyy-MM-dd-HH-mm} - Minute format%d{yyyy-ww} - Week-based rolling%i - Integer index for size-based splitting within time periods.gz extension - Automatic gzip compression.zip extension - Automatic ZIP compressionapp.%d{yyyy-MM-dd}.log - Daily files: app.2023-12-01.logapp.%d{yyyy-MM-dd}.%i.log.gz - Daily with size splitting: app.2023-12-01.0.log.gzapp.%i.log.zip - Fixed window with ZIP: app.1.log.zip, app.2.log.zipInstall with Tessl CLI
npx tessl i tessl/maven-ch-qos-logback--logback-core