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

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: ...

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>

RollingFileAppender not working when used inside SiftingAppender

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.

logback's RollingFileAppender is not rolling file with EvaluatorFilter

Logback framework's ch.qos.logback.core.rolling.RollingFileAppender is not rolling files when EvaluatorFilter is used as following:
<appender name="APPLICATION-INFO"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.root}/${CONTEXT_NAME}-INFO.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.root}/${CONTEXT_NAME}-INFO-%d{yyyyMMdd}.log
</fileNamePattern>
</rollingPolicy>
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator>
<expression>return (level == INFO || level == WARN);</expression>
</evaluator>
<OnMismatch>DENY</OnMismatch>
<OnMatch>ACCEPT</OnMatch>
</filter>
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="com.xxx.yyyy.zzz.logging.json.JsonLayout">
<timestampFormat>${timestampFormat}</timestampFormat>
<includeMDC>false</includeMDC>
</layout>
<immediateFlush>true</immediateFlush>
</encoder>
</appender>
But the the following configuration rolls the log file.
<appender name="APPLICATION-ERROR"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.root}/${CONTEXT_NAME}-ERROR.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.root}/${CONTEXT_NAME}-ERROR-%d{yyyyMMdd}.log
</fileNamePattern>
</rollingPolicy>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="com.xxx.yyy.zzz.logging.json.JsonLayout">
<timestampFormat>${timestampFormat}</timestampFormat>
<includeMDC>false</includeMDC>
</layout>
<immediateFlush>true</immediateFlush>
</encoder>
</appender>
I'm a bit lazy to test that locally but I have a clue what might be wrong :-) In the docs of logback it is written:
For various technical reasons, rollovers are not clock-driven but
depend on the arrival of logging events. For example, on 8th of March
2002, assuming the fileNamePattern is set to yyyy-MM-dd (daily
rollover), the arrival of the first event after midnight will trigger
a rollover. If there are no logging events during, say 23 minutes and
47 seconds after midnight, then rollover will actually occur at
00:23'47 AM on March 9th and not at 0:00 AM.
Based on this a possible guess is that there was no proper logging event accepted by the default JaninoEventEvaluator that you configured.
Another speculation is that you do not refer the appender properly but there are not enough details about this in the question.

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;
}