RollingFileAppender not working when used inside SiftingAppender - logback

I have the following logback setup
<appender name="TEST-SIFT" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator class="..."/>
<sift>
<appender name="ROLL-${fileName}" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>../log/${fileName}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>../log/${fileName}%i.log</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>10</maxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>5MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n</pattern>
</encoder>
</appender>
</sift>
</appender>
The discriminator class returns a value by parsing the loggerName. The key is defined as "fileName".
The logs rollover fine when I test just the RollingFileAppender (after replacing the variable references of ${fileName} with a static value) but when I have it nested under SiftingAppender, the logs do not roll over. I tested the sifting appender with "FileAppender" and it is able to create the right file name based on the discriminator.
I also tested the same configuration by using the discriminator as
<discriminator>
<key>fileName</key>
<defaultValue>appname</defaultValue>
</discriminator>
and removing the class tag. This creates appname.log but does not roll over.
Setting debug="true" did not write any additional information to the log file.
Am I missing something here? How do I implement RollingFileAppender inside a SiftingAppender?

I figured out the issue with my setup. My logback.xml has to two RollingFileAppenders (one nested in the sifter and one outside). Appender A was writing to application.log and Appender B in some circumstances was writing to application.log as well (i.e. ${fileName} evaluated to application). So if I remove appender A or rename Appender A's fileName, the logs roll over as configured. This probably means Appender A or B could not close and rename the file because the other appender still has a lock on it?
To test this I used an AsyncAppender as follows:
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
<appender-ref ref="FILE" />
</appender>
where "FILE" is the name of Appender A. Using this configuration works but I see some strange behavior where the files do not rollover at the exact size specified and in some cases, the files are renamed with index 10 and get deleted automatically. Since this behavior is not very reliable, for now I got rid of Appender A.

Related

Conditionally format logs in logback

I'm currently formatting my logs in logback like below. However, when I run my app locally I don't want all this metadata gunking up my logs, I just wanna see the message. How can I say "If an environment variable = 'local' then format this way, else format as below"?
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<Target>System.out</Target>
<encoder>
<Pattern>
date=%d{yyyy-MM-dd HH:mm:ss} | rte=${RTEID} | runId=%X{RunId} | interface=%X{Interface} | class=%class{0}.%method | level=%-5level | message=%msg %replace(%xException){'\n','\u2028'}%nopex%n
</Pattern>
</encoder>
</appender>
bit late. But if you are using spring boot you can use logback-spring.xml
and inside you can do something like
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<springProfile name="dev-local">
<pattern>FIST PATTERN</pattern>
</springProfile>
<springProfile name="!dev-local">
<pattern>SECOND PATTERN</pattern>
</springProfile>
</encoder>
</appender>

Logback: Can I change the log level names? (WARN -> WARNING)

logback:
timestamp INFO msg...
timestamp WARN msg...
timestamp INFO msg...
classic java logging (JUL):
timestamp INFO msg...
timestamp WARNING msg...
timestamp INFO msg...
I prefer the WARNING level to be longer than INFO, so I can easily distinguish it visually when scanning log output.
You could specify different logback patterns to achieve what you want - you can send info level logging to an appender which uses a standard layout and then warn to a different appender which uses the word WARNING instead:
<configuration debug="true">
<appender name="info" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>DENY</onMatch>
<onMismatch>ACCEPT</onMismatch>
</filter>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>
%d{"ISO8601", UTC} %p %m%n
</pattern>
</encoder>
</appender>
<appender name="warn" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>
%d{"ISO8601", UTC} WARNING %m%n
</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="info"/>
<appender-ref ref="warn"/>
</root>
</configuration>
The %p parameter is substituted with the original message log level so we keep that for the info pattern, for the warn pattern we don't use %p but rather use the constant WARNING.
This config would sit in your logback.xml file in resources root.
EDIT
Changed xml config to use filters and only have one root logger
The idea here is to filter out everything EXCEPT warn level for the first appender, and then on the second only accept warn level and override the log to show WARNING
sample output:
2018-11-08 10:52:40,460 WARNING Exception calculating properties for model(...)
2018-11-08 10:52:40,757 INFO Generating unique operation named: ...

Logback fire mail for warnings

I want to configure Logback to fire an email whenever any warnings are found on server.
Right now it is already configure for error level we are getting mails when any error occurred. However same code with changing root level to warn doesn't work.
All sender, receiver, host etc. details are same for which use in error SMTP appender so it's not a server issue. Below is my code.
<appender name="EMAILWARN" class="ch.qos.logback.classic.net.SMTPAppender">
<smtpHost>XXXX</smtpHost>
<to>XXXX</to>
<!-- additional destinations are possible -->
<from>XXXX</from>
<!--
<discriminator class="ch.qos.logback.classic.sift.MDCBasedDiscriminator">
<key>req.remoteHost</key> visit http://logback.qos.ch/manual/mdc.html#mis for different key values
<defaultValue>default</defaultValue>
</discriminator>
-->
<!-- <subject>RCM-Error: ${HOSTNAME} %X{req.remoteHost} %logger - %m</subject> -->
<subject>Error: ${HOSTNAME} - %m %logger</subject>
<!-- <layout class="ch.qos.logback.classic.PatternLayout"> -->
<layout class="ch.qos.logback.classic.html.HTMLLayout">
<pattern>%date%X{REMOTE_ADDR}%X{USER_NAME}%level%logger%message</pattern>
</layout>
<cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTrackerImpl">
<bufferSize>20</bufferSize> <!-- set number of log entry to send per email -->
</cyclicBufferTracker>
</appender>
<root level="warning">
<appender-ref ref="EMAILWARN" />
</root>
ch.qos.logback.classic.net.SMTPAppender use an evaluator to trigger the email send procedure. The default one triggers at ERROR level.
So what you need is an evaluator that tiggers at WARN level (and above)
<appender ... class="ch.qos.logback.classic.net.SMTPAppender">
...
<evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator">
<expression>return level >= WARN;</expression>
</evaluator>
...
</appender>
I'm pretty sure that warning is not a valid logback level.
Try changing your root logger level to warn:
<root level="warn">
<appender-ref ref="EMAILWARN" />
</root>
You can use filters as below, which will select log levels error and warn
<appender name="EMAILWARN" class="ch.qos.logback.classic.net.SMTPAppender">
<!-- rest of your configurations -->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
</appender>

Logback - Multiple syslog appenders

I'm logging to syslog with a syslog appender as shown below:
<appender name="SYSLOG" class="ch.qos.logback.classic.net.SyslogAppender">
<syslogHost>localhost</syslogHost>
<facility>LOCAL6</facility>
<suffixPattern>app: %logger{20} %msg</suffixPattern>
</appender>
But I've got a new requirement where I want to send some logs to the "LOCAL5" facility instead of LOCAL6. I've read the logback configuration documentation http://logback.qos.ch/manual/configuration.html but I'm still not sure how to do this.
You can use two syslog appenders one for LOCAL6 and other for LOCAL5
<appender name="SYSLOG" class="ch.qos.logback.classic.net.SyslogAppender">
<syslogHost>localhost</syslogHost>
<facility>LOCAL6</facility>
<suffixPattern>app: %logger{20} %msg</suffixPattern>
</appender>
<appender name="SYSLOG1" class="ch.qos.logback.classic.net.SyslogAppender">
<syslogHost>localhost</syslogHost>
<facility>LOCAL5</facility>
<suffixPattern>app: %logger{20} %msg</suffixPattern>
</appender>
Advantage is that you a customize the logs( some logs) using filters, pattern, logger names etc. And SyslogAppender extends UnsyncronizedAppender.
Reason being you cannot use single appender is that method facilityStringToint(String facilityStr) in class SyslogAppender.java accepts String which then compares which standard facility using equals.
Example
if ("KERN".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_KERN;
}

Logback daily rolling incorrect

We are using quite a basic daily rolling configuration with logback, and it seems not to function properly. Application creates rolled (previous day) file usually in first minute after midnight. The yyyyMMdd fraction of file name contans previous day, that's correct. But messages in log are not from previous but from new day, only that 30-40 seconds !
For example, bim.2013-08-21.log file contains records with timestamps from 2013.08.22 00:00:00 to 2013.08.22 00:00:42. And all messages from previous day gets lost.
Also, there was some "lucky" exceptions when rolling started in the mid of the day , e.g. 16:00 , so we got more records rolled - from current day.
Logback version is 1.0.13
logback-test.xml :
<configuration scan="true" scanPeriod="10 minutes">
<contextName>bim</contextName>
<property name="LOG_DIR" value="/usr/share/apache-tomcat-7.0.41/logs" />
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-5level %m \(%logger{36}:%L\)%n</pattern>
</encoder>
</appender>
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_DIR}/bim.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- daily rollover -->
<fileNamePattern>${LOG_DIR}/bim.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>5</maxHistory>
<cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %m \(%logger{36}:%L\)%n</pattern>
</encoder>
</appender>
<logger name="com.bim" level="DEBUG" />
<logger name="org.springframework.web.servlet.mvc.support" level="WARN" />
<logger name="org.springframework.web.servlet.mvc.annotation" level="WARN" />
<root level="INFO">
<!--appender-ref ref="console" /-->
<appender-ref ref="file" />
</root>
I have not found any traces of similar problems by search, so your help will be greatly appreciated.
I can't see what part are you missing over here. Even I have done the same and its working fine. Please check below link and try it in the same fashion :
https://github.com/abdulwaheed18/Slf4jTutorial/blob/master/sample7.xml