I wrote code based on this solution: https://gist.github.com/umangmathur92/a65f67c01e2b425289b8
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
lc.reset();
final String LOG_DIR = context.getExternalCacheDir() + File.separator + ".ts";
RollingFileAppender<ILoggingEvent> rollingFileAppender = new RollingFileAppender<>();
rollingFileAppender.setAppend(true);
rollingFileAppender.setContext(lc);
rollingFileAppender.setLazy(true);
rollingFileAppender.setFile(LOG_DIR + File.separator + "ts.log");
SizeBasedTriggeringPolicy<ILoggingEvent> trigPolicy = new SizeBasedTriggeringPolicy<>();
trigPolicy.setMaxFileSize(new FileSize(1024 * 256));
trigPolicy.setContext(lc);
trigPolicy.start();
FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy();
rollingPolicy.setContext(lc);
rollingPolicy.setParent(rollingFileAppender);
rollingPolicy.setFileNamePattern(LOG_DIR + File.separator + "ts.%i.log");
rollingPolicy.setMinIndex(1);
rollingPolicy.setMaxIndex(1);
rollingPolicy.start();
rollingFileAppender.setTriggeringPolicy(trigPolicy);
rollingFileAppender.setRollingPolicy(rollingPolicy);
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setPattern("%msg%n");
encoder.setContext(lc);
encoder.start();
rollingFileAppender.setEncoder(encoder);
rollingFileAppender.start();
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.addAppender(rollingFileAppender);
But this is not what I wanted to do. This code deletes all the file when reaches specefied limit and begins to write a new one (so, after reaching 256KB limit file then takes 10KB for example).
I want to limit file size to 256KB and I want to clear the oldest lines to release space for new ones.
Example:
Line 1 sample text.
Line 2 sample text.
Line 3 sample text.
Line 4 sample text.
Line 5 sample text.
Imagine, that these lines takes 256KB, and when I write new line:
Line 6 sample text.
I want this file to look like:
Line 2 sample text.
Line 3 sample text.
Line 4 sample text.
Line 5 sample text.
Line 6 sample text.
This would require to rewrite the whole file whenever a line is deleted from the beginning. Therefore, this would be a performance bottleneck. The usual solution is to start a new log file when the old one has reached a certain size.