I'm using https://logback.qos.ch/ for a long running Java program. Is there a way to configure some appender to log only the first N lines of a program?
For example, my program logs important information at startup but if I use a rolling file appender, the logs at startup are eventually deleted.
I found how to do this in log4j
as follows:
<appender name="StartupAppender" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="${samza.log.dir}/${samza.container.name}-startup.log" />
<param name="MaxFileSize" value="256MB" />
<param name="MaxBackupIndex" value="1" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} [%p] %m%n" />
</layout>
</appender>
<logger name="STARTUP_LOGGER" additivity="false">
<level value="info" />
<appender-ref ref="StartupAppender"/>
</logger>
How do I do this in Logback?
There is no canned, pre-existing Logback appender which will "Log only first N lines with Logback" I'd suggest that you use Logback's existing implementations of rollingPolicy
and triggeringPolicy
to create a Logback configuration which matches the configuration you had working in Log4J.
The Logback equivalent of the StartupAppender
in your question is:
<appender name="StartupAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${samza.log.dir}/${samza.container.name}-startup.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>${samza.log.dir}/${samza.container.name}-startup.log.%i.log</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>1</maxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>256MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} [%p] %m%n</pattern>
</encoder>
</appender>
<logger name="STARTUP_LOGGER" additivity="false">
<level value="info" />
<appender-ref ref="StartupAppender"/>
</logger>
This will behave the same as your Log4J StartupAppender
but just like that appender it is not guaranteed to retain the "first N lines of a program" since it will rollover on reaching 256MB. However, since you are only associating this appender with the logger: STARTUP_LOGGER
it seems likely that 256MB would be more than enough space to retain a lengthy history of 'startup logs'.