Logback - Layout & Pattern in logback.xml - spring-boot

I am using logback with slf4j for logging in Spring Boot application. I have created a custom layout class because all log statements are to be wrapped as a json. I have configured the logback-spring.xml as show below to take the custom layout. It works!
Issue is I am unable to apply the pattern. Only either the layout works (or) the pattern. What I want is always on log, go to layout class and then apply the pattern before logging.
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${user.home}/logs/sample.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${user.home}/logs/sample_%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!-- how many days to keep the files -->
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="com.test.test.payment.core.logging.SampleLogLayout" >
</layout>
</encoder>
*<!-- <encoder>
<charset>UTF-8</charset>
<Pattern>{"#timestamp": "%d{yyyy-MM-dd HH:mm:ss.SSS}", "priority": "%p", "application": "payment",
"class": "%C", "file": "%F:%L", "payload": %m }%n
</Pattern>
</encoder>-->*
</appender>
Here's the SampleLogLayout class:
public class SampleLogLayout extends LayoutBase<LoggingEvent> {
#Override
public String doLayout(LoggingEvent event) {
String renderedMessage = event.getMessage();
if (!isJson(renderedMessage)) {
Throwable throwable = null;
if (event.getLevel().equals(Level.ERROR) || event.getLevel().equals(Level.WARN)) {
final IThrowableProxy throwableProxy = event.getThrowableProxy();
if ((throwableProxy != null) && (throwableProxy instanceof ThrowableProxy)) {
ThrowableProxy proxy = (ThrowableProxy) throwableProxy;
throwable = proxy.getThrowable();
}
String message = LogErrorMessage.create(CommonCoreErrors.GENERIC_ERROR)
.message(renderedMessage).exception(throwable).build();
return message;
} else {
return LogMessage.create(renderedMessage).build();
}
}
return renderedMessage;
}
private boolean isJson(String msg) {
if (null == msg) {
return false;
} else {
return msg.startsWith("{") && msg.endsWith("}");
}
}
}

I started to reproduce this in order to provide a complete solution but the absence of LogMessage and LogErrorMessage made that a bit tricky.
However, it looks to me like you just want to log in JSON format, not just the message but also the metadata such as timestamp, priority etc.
This can be achieved by using the JsonLayout. Here's an example of the layout configuration:
<layout class="ch.qos.logback.contrib.json.classic.JsonLayout">
<jsonFormatter class="ch.qos.logback.contrib.jackson.JacksonJsonFormatter">
<prettyPrint>false</prettyPrint>
</jsonFormatter>
<timestampFormat>yyyy-MM-dd' 'HH:mm:ss.SSS</timestampFormat>
<appendLineSeparator>true</appendLineSeparator>
<includeContextName>false</includeContextName>
</layout>
With that configuration the following log invocation ...
logger.info("{\"a\": 1, \"b\": 2}");
... will emit:
{"timestamp":"2017-10-05 10:51:34.610","level":"INFO","thread":"main","logger":"com.stackoverflow.logback.LogbackTest","message":"{\"a\": 1, \"b\": 2}"}
You can include MDC too, for example ...
MDC.put("application", "payment");
logger.info("{\"a\": 1, \"b\": 2}");
... will emit:
{"timestamp":"2017-10-05 10:52:56.088","level":"INFO","thread":"main","mdc":{"application":"payment"},"logger":"com.stackoverflow.logback.LogbackTest","message":"{\"a\": 1, \"b\": 2}"}
That's quite close to your desired output and JsonLayout is extensible so you could ...
Override toJsonMap() to change names of the keys e.g. replace timestamp with #timestamp, replace message with payload
Implement addCustomDataToJsonMap() to add other key:value pairs to the log event
So, I think you could achieve your desired output using the pre-existing JsonLayout rather than writing your own.
More details on Logback JSON extensions here.
The Maven coordinates are:
<dependency>
<groupId>ch.qos.logback.contrib</groupId>
<artifactId>logback-json-classic</artifactId>
<version>0.1.5</version>
</dependency>
<dependency>
<groupId>ch.qos.logback.contrib</groupId>
<artifactId>logback-json-core</artifactId>
<version>0.1.5</version>
</dependency>
<dependency>
<groupId>ch.qos.logback.contrib</groupId>
<artifactId>logback-jackson</artifactId>
<version>0.1.5</version>
</dependency>

Related

Truncate individual log messages above a certain character count with Spring logback

I would like to reduce the size of certain logs using logback (I attempted to use Pattern layout with with a pattern of %.100000msg to limit the max size to one hundred thousand but had no luck), the large(over 1 million characters caused by a few REST GET calls) logs are causing Elastic to slow down when searching for certain information.
What would be the best practice to overcome this?
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<appender name="Console"
class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%.30msg
</Pattern>
</layout>
</appender>
<logger name="" level="INFO"/>
I solved this by refering to this documentation to create a custom converter. The property was an extra, it was implemented to allow for configuration within the xml file.
<property scope="context" name="max-message-length" value="100000"/>
<conversionRule conversionWord="boundedMsg"
converterClass="za.co.ksdc.qadee.config.TruncationCustomLogConverter" />
The following java class was implemented to truncate the log message:
public class TruncationCustomLogConverter extends ClassicConverter {
#Override
public String convert(ILoggingEvent event) {
int maxMessageLength = Integer.parseInt(getContext().getProperty("max-
message-length"));
String formattedMessage = event.getFormattedMessage();
if (formattedMessage == null ||
formattedMessage.length() < maxMessageLength) {
return formattedMessage;
}
return new StringBuilder(maxMessageLength)
.append(formattedMessage, 0, maxMessageLength)
.toString();
}
}

Logback and JsonLayout: can't pass custom fields

I have this configuration in my logback.xml into a Spring Web Application (NO Spring Boot).
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="ch.qos.logback.contrib.json.classic.JsonLayout">
<timestampFormat>yyyy-MM-dd'T'HH:mm:ss.SSSX</timestampFormat>
<timestampFormatTimezoneId>Etc/UTC</timestampFormatTimezoneId>
<jsonFormatter class="ch.qos.logback.contrib.jackson.JacksonJsonFormatter">
<prettyPrint>true</prettyPrint>
</jsonFormatter>
</layout>
<customFields>{"appname":"foobar"}</customFields>
</encoder>
</appender>
<!-- LOG everything at INFO level -->
<root level="INFO">
<appender-ref ref="Console" />
</root>
</configuration>
The JSON layout works fine but custom fields as "appname": "foobar" are not printed:
{
"timestamp" : "2020-06-10T14:55:25.534Z",
"level" : "INFO",
"thread" : "Catalina-utility-1",
"logger" : "org.springframework.web.servlet.DispatcherServlet",
"message" : "FrameworkServlet 'dispatcher': initialization completed in 72 ms",
"context" : "default"
}
What am I doing wrong?
SOLUTION
I was using the wrong libraries for my needs:
logback-jackson
logback-json-classic
Because of the fact that I need to process logs through Logstash I've corrected my configuration like this:
pom.xml
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>6.4</version>
</dependency>
logback.xml
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<customFields>{"customer":"X", "appname":"Y", "environment":"dev"}</customFields>
</encoder>
</appender>
and now It works fine.
I just stumbled this question because I had the same problem, and I found a solution, with logback-jackson and logback-json-classic.
Option 1: Per-Thread via Mapped Diagnostic Context (MDC)
SLF4j's Mapped Diagnostic Context is a per-thread key-value store that we can use to write custom structured data to the log output.
MDC.put("customKey", "customValue");
Logback's JsonLayout will automatically print this value under a special mdc JSON object without any further configuration.
{ [...], "mdc": {"customKey", "customValue"}}
Note that the MDC is constructed per thread and if it is empty, no mdc field is printed to the log output.
Option 2: Global (for all threads)
If you want custom fields to appear at the JSON output's root, you need to create a custom, but simple Layout class that extends JsonLayout. JsonLayout provides us with a addCustomDataToJsonMap we can override.
package com.mypackage;
import ch.qos.logback.contrib.json.classic.JsonLayout;
public class CustomJsonLayout extends JsonLayout {
#Override
protected void addCustomDataToJsonMap(Map<String, Object> map, ILoggingEvent event) {
map.put("customKey", "customValue");
}
}
Now, you just need to tell Logback to use CustomJsonLayout instead of JsonLayout in your logback.xml file and keep the rest the same.
<layout class="com.mypackage.CustomJsonLayout">
...
</layout>
Now, any log message will have the following output:
{ ..., "customKey": "customValue"}

Springboot Event Logging

I have a scheduled task in a fixed rate, that reads a queue.
Each message that comes from the queue has an ID.
I wanna know if it's possible split the log by ID, appending to a different file.
I was thinking about use aspects or a custom appender, one of these can do the job for me?
Thanks.
Well, after some search I've remembered of MDC (Mapped Diagnostic Context) wich can do what I want with almost no workarounds.
I just need to add a SiftingAppender to the logback-spring.xml like this:
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<appender name="SIFT" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator>
<key>checkoutId</key>
<defaultValue>system</defaultValue>
</discriminator>
<sift>
<appender name="${checkoutId}" class="ch.qos.logback.core.FileAppender">
<file>${checkoutId}.log</file>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{HH:mm:ss:SSS} | %-5level | %thread | %logger{20} | %msg%n%rEx</pattern>
</layout>
</appender>
</sift>
</appender>
<root level="INFO">
<appender-ref ref="SIFT" />
</root>
</configuration>
Than I call like that:
#Scheduled(initialDelayString = "${consumeStart:10000}", fixedRateString = "${consumeRate:5000}")
private void task() {
try {
val message = queue.get(timeout);
if (message != null) {
MDC.put("checkoutId", message.toString());
. . .
}
} finally {
MDC.remove("checkoutId");
}
}

Sending Logback logs to LogStash via RabbitMQ using JSON Encoder (Spring)

I am using Spring Boot (1.5.4). I wish to send (logback) logs from my services to Logstash via RabbitMQ in a JSON format rather than plain text. This will save me from having to set up a filter on the Logstash side so that formatting can be controlled on the application side (using a Logback Encoder).
I am aware of the Spring logback AMQP Appender for RabbitMQ org.springframework.amqp.rabbit.logback.AmqpAppender however this uses a Layout (plain text) rather than formatted JSON. I would like to use the LogStash Encoder net.logstash.logback.encoder.LogstashEncoder. I would like to use the Appender with the Encoder (I want it all :").
I first extended the AMQPAppender to add the Encoder like so:-
package nz.govt.mpi.util;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.logback.AmqpAppender;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.encoder.Encoder;
import lombok.Getter;
import lombok.Setter;
public class AmqpLogbackAppender extends AmqpAppender {
#Getter
#Setter
private Encoder<ILoggingEvent> encoder;
/**
* We remove the default message layout and replace with the JSON {#link Encoder}
*/
#Override
public Message postProcessMessageBeforeSend(Message message, Event event) {
return new Message(this.encoder.encode(event.getEvent()), message.getMessageProperties());
}
#Override
public void start() {
super.start();
encoder.setContext(getContext());
if (!encoder.isStarted()) {
encoder.start();
}
}
#Override
public void stop() {
super.stop();
encoder.stop();
}
}
And then I set up the logback-spring.xml configuration file like so:-
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<springProperty scope="context" name="rabbitMQHost" source="logback.amqp.host" defaultValue="localhost"/>
<springProperty scope="context" name="rabbitMQPort" source="logback.amqp.port" defaultValue="5672"/>
<springProperty scope="context" name="rabbitMQUsername" source="spring.rabbitmq.username" />
<springProperty scope="context" name="rabbitMQPassword" source="spring.rabbitmq.password" />
<springProperty scope="context" name="rabbitMQExchangeName" source="logback.amqp.exchange.name" defaultValue="mpi.tradedev"/>
<springProperty scope="context" name="rabbitMQRoutingKey" source="logback.amqp.routing.key" defaultValue="mpi.tradedev.logging"/>
<springProperty scope="context" name="serviceName" source="spring.application.name" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread, %X{X-B3-TraceId:-},%X{X-B3-SpanId:-}] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender name="AMQP" class="nz.govt.mpi.util.AmqpLogbackAppender">
<!-- layout is required but ignored as using the encoder for the AMQP message body -->
<layout><pattern><![CDATA[ %level ]]></pattern></layout>
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<customFields>{"serviceName": "${serviceName}"}</customFields>
</encoder>
<!-- RabbitMQ connection -->
<host>${rabbitMQHost}</host>
<port>${rabbitMQPort}</port>
<username>${rabbitMQUsername}</username>
<password>${rabbitMQPassword}</password>
<exchangeName>${rabbitMQExchangeName}</exchangeName>
<routingKeyPattern>${rabbitMQRoutingKey}</routingKeyPattern>
<declareExchange>true</declareExchange>
<exchangeType>topic</exchangeType>
<generateId>true</generateId>
<charset>UTF-8</charset>
<durable>true</durable>
<deliveryMode>PERSISTENT</deliveryMode>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
<appender-ref ref="AMQP" />
</root>
</configuration>
I lastly added the required properties to the application.properties file like so:-
spring.application.name=my-app
logback.amqp.host=localhost
logback.amqp.port=5672
logback.amqp.exchange.name=ex_logstash
logback.amqp.routing.key=my-app.logging
spring.rabbitmq.username=rquser
spring.rabbitmq.password=rqpass
I also had to set up the necessary user account in RabbitMQ. When the application runs it creates the topic (ex_logstash) but you must create a queue (qu_logstash) that is bound to that topic with the routing key match (my-app.*).
You then create a logstash configuration to match the queue name.
ex_logstash -> qu_logstash
The logstash.json configuration file example:-
input {
rabbitmq {
host => "localhost"
queue => "qu_logstash"
durable => true
exchange => "ex_logstash"
key => "my-app.*"
threads => 10
type => "topic"
prefetch_count => 200
port => 5672
user => "rquser"
password => "rqpass"
}
}
On the application side you will need the required dependencies in your pom.xml. These are the ones I am using that cover the required classes YMMV:-
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>4.9</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>

Debug logging of ResponseBody by Springframework

I have a scenario where I send some sensitive data in the ResponseBody of a spring controller. Spring logs the entire response body in DEBUG mode, where I can see the sensitive data also. Now if I configure my app to print only INFO logs or higher, this won't be displayed, but that is not a fool proof method, since its possible that DEBUG mode could be turned on accidentally.
Is there anyway I can disable certain fields in the response body from being logged by Spring?
Thanks
My suggestion would be that you implement a custom converter for logback (if that is your logging library)
http://logback.qos.ch/manual/layouts.html#customConversionSpecifier
It enables you to convert your logging data and blur out any data that should be removed from the message.
From the documentation it is pretty straight forward
public class MySampleConverter extends ClassicConverter {
long start = System.nanoTime();
#Override
public String convert(ILoggingEvent event) {
long nowInNanos = System.nanoTime();
return Long.toString(nowInNanos-start);
}
}
And the config
<configuration>
<conversionRule conversionWord="nanos"
converterClass="chapters.layouts.MySampleConverter" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%-6nanos [%thread] - %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration>
If you're using Log4j you can implement a custom filter which would mask the data per your layout
http://vozis.blogspot.sg/2012/02/log4j-filter-to-mask-payment-card.html
Edit
The final easier solution turned out to be to override toString of the return object. Spring uses toString to log the return message

Resources