<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tayfun Akgüç on Medium]]></title>
        <description><![CDATA[Stories by Tayfun Akgüç on Medium]]></description>
        <link>https://medium.com/@dev.akguc?source=rss-f23a29371804------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*h2DhPxU4p87rtDgE</url>
            <title>Stories by Tayfun Akgüç on Medium</title>
            <link>https://medium.com/@dev.akguc?source=rss-f23a29371804------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:30:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dev.akguc/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Integrating BetterStack Logtail in Spring Boot with Logback]]></title>
            <link>https://medium.com/@dev.akguc/integrating-betterstack-logtail-in-spring-boot-with-logback-f2f8d9edaddc?source=rss-f23a29371804------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2f8d9edaddc</guid>
            <category><![CDATA[slf4j]]></category>
            <category><![CDATA[logging-and-monitoring]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[logback]]></category>
            <dc:creator><![CDATA[Tayfun Akgüç]]></dc:creator>
            <pubDate>Sat, 05 Oct 2024 18:29:07 GMT</pubDate>
            <atom:updated>2024-10-05T18:29:07.592Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explore how to integrate BetterStack with Spring Boot to achieve robust and traceable logging for your application. The focus will be on configuring Logback for structured JSON logging and setting up an MDC (Mapped Diagnostic Context) filter to include trace IDs in every log entry. This setup allows for better observability and queryable logs, making it easier to monitor and troubleshoot your application on BetterStack.</p><h4><strong>Adding Dependencies</strong></h4><p>We need the following dependencies for the integration.</p><pre>&lt;dependencies&gt;<br> &lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-logging&lt;/artifactId&gt;<br>  &lt;version&gt;3.2.10&lt;/version&gt;<br> &lt;/dependency&gt;<br> &lt;dependency&gt;<br>  &lt;groupId&gt;com.logtail&lt;/groupId&gt;<br>  &lt;artifactId&gt;logback-logtail&lt;/artifactId&gt;<br>  &lt;version&gt;0.3.4&lt;/version&gt;<br> &lt;/dependency&gt;<br> &lt;dependency&gt;<br>  &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;<br>  &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;<br>  &lt;version&gt;2.15.4&lt;/version&gt;<br> &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><h4><strong>Add Logtail API Token To Application Properties</strong></h4><p>PR: <a href="https://github.com/tayfun-akguc/spring-boot-dev-notes/pull/8/files">https://github.com/tayfun-akguc/spring-boot-dev-notes/pull/8/files</a></p><p>To get api token for the integration, you have to create source in Better Stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mkcd8cohNk8Wlt72VnjiMw.png" /></figure><p>After creating the source, you will be able to get the <strong>Source token.</strong></p><p>The src/main/resources/application.yml :</p><pre>spring:<br>  application:<br>    name: better-stack-application-logging<br>  # Set the default profile as local<br>  profiles:<br>    default: local</pre><p>The src/main/resources/application-local.yml :</p><pre># Do not need to define the following properties<br>#logtail:<br>#  sourceToken: &lt;YOUR_SOURCE_TOKEN&gt;</pre><p>The src/main/resources/application-dev.yml :</p><pre>logtail:<br>  sourceToken: &lt;YOUR_SOURCE_TOKEN&gt;</pre><h4>Logback Configuration</h4><p>PR: <a href="https://github.com/tayfun-akguc/spring-boot-dev-notes/pull/3/files">https://github.com/tayfun-akguc/spring-boot-dev-notes/pull/3/files</a></p><p>Logback is configured via an XML configuration file. Create or update the src/main/resources/logback.xml file with the following configuration to send logs to BetterStack Logtail.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;configuration&gt;<br>    &lt;!-- Application Name --&gt;<br>    &lt;springProperty scope=&quot;context&quot; name=&quot;appName&quot; source=&quot;spring.application.name&quot;/&gt;<br><br>    &lt;!-- Logtail API Token --&gt;<br>    &lt;springProperty scope=&quot;context&quot; name=&quot;logtailToken&quot; source=&quot;logtail.sourceToken&quot;/&gt;<br><br>    &lt;!-- Logtail Appender --&gt;<br>    &lt;appender name=&quot;Logtail&quot; class=&quot;com.logtail.logback.LogtailAppender&quot;&gt;<br>        &lt;appName&gt;${appName}&lt;/appName&gt;<br>        &lt;sourceToken&gt;${logtailToken}&lt;/sourceToken&gt;<br>        &lt;mdcFields&gt;traceId&lt;/mdcFields&gt;<br>        &lt;mdcTypes&gt;string&lt;/mdcTypes&gt;<br>    &lt;/appender&gt;<br><br>    &lt;!-- Console Appender --&gt;<br>    &lt;appender name=&quot;Console&quot; class=&quot;ch.qos.logback.core.ConsoleAppender&quot;&gt;<br>        &lt;encoder&gt;<br>            &lt;pattern&gt;%green(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1}) [%highlight(%X{traceId})] : %msg%n%throwable&lt;/pattern&gt;<br>        &lt;/encoder&gt;<br>    &lt;/appender&gt;<br><br>    &lt;root level=&quot;INFO&quot;&gt;<br>        &lt;appender-ref ref=&quot;Console&quot; /&gt;<br>        &lt;!-- Add the logtail appender conditionally --&gt;<br>        &lt;springProfile name=&quot;!local&quot;&gt;<br>            &lt;appender-ref ref=&quot;Logtail&quot; /&gt;<br>        &lt;/springProfile&gt;<br>    &lt;/root&gt;<br>&lt;/configuration&gt;</pre><ol><li><strong>springProperty</strong>: These elements define properties to be injected from the Spring context. appName gets its value from spring.application.name, and logtailToken gets its value from logtail.sourceToken.</li><li><strong>LogtailAppender </strong>: This is a custom appender for sending logs to Logtail. <strong>mdcFields</strong> : Specifies which MDC fields should be included in the logs. <strong>mdcTypes</strong> : Specifies the types of the MDC fields.<br>To include additional MDC fields in your logs, update the mdcFields and the mdcTypes fields. <br>&lt;mdcFields&gt;traceId,aString,anInt&lt;/mdcFields&gt;<br>&lt;mdcTypes&gt;string,string,int&lt;/mdcTypes&gt; <br>We will implement a <strong>Filter </strong>to generate and inject the traceId into the logging context.</li><li><strong>root</strong> : Defines the default logging behavior. <br><strong>springProfile</strong> : Conditional configuration based on the Spring profile. If the active profile is not local, it also includes the Logtail appender. It’s not necessary to send logs while developing a feature locally.</li></ol><h4>Implementing The Filter</h4><p>PR: <a href="https://github.com/tayfun-akguc/spring-boot-dev-notes/pull/4/files">https://github.com/tayfun-akguc/spring-boot-dev-notes/pull/4/files</a></p><p>We start by creating a class named MdcFilter that implements the Filter interface. This filter will be responsible for generating a unique trace identifier for each request and attaching it to the MDC.</p><pre>package com.spring.boot.dev.notes.filter;<br><br>import jakarta.servlet.*;<br>import jakarta.servlet.http.HttpServletRequest;<br>import org.slf4j.MDC;<br>import org.springframework.stereotype.Component;<br><br>import java.io.IOException;<br>import java.util.UUID;<br><br>@Component<br>@Order(1)<br>public class MdcFilter implements Filter {<br><br>    private static final String TRACE_ID_HEADER = &quot;X-Trace-Id&quot;;<br>    private static final String MDC_TRACE_ID_KEY = &quot;traceId&quot;;<br><br>    @Override<br>    public void doFilter(<br>            ServletRequest servletRequest,<br>            ServletResponse servletResponse,<br>            FilterChain filterChain) throws IOException, ServletException {<br>        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;<br>        MDC.put(MDC_TRACE_ID_KEY, getOrCreateTraceId(httpServletRequest));<br><br>        try {<br>            filterChain.doFilter(servletRequest, servletResponse);<br>        } finally {<br>            MDC.clear();<br>        }<br>    }<br><br>    private String getOrCreateTraceId(HttpServletRequest httpServletRequest) {<br>        var traceId = httpServletRequest.getHeader(TRACE_ID_HEADER);<br>        return traceId != null<br>                ? traceId<br>                : String.valueOf(UUID.randomUUID());<br>    }<br>}</pre><p>By implementing this MdcFilter, every log entry will include a unique traceId</p><p>The @Component annotation ensures that Spring Boot detects and registers the filter as a bean.</p><p>The @Order(1) annotation sets the order of the filter, determining when it should be applied in relation to other filters.</p><h4>Creating The Data Transfer Objects</h4><p>PR: <a href="https://github.com/tayfun-akguc/spring-boot-dev-notes/pull/5/files">https://github.com/tayfun-akguc/spring-boot-dev-notes/pull/5/files</a></p><p>First, I created the BaseDto class is an abstract class that provides a common functionality for converting any subclass object to a JSON string. This class includes a toJson() method, which uses Jackson&#39;s ObjectMapper to transform the object into a JSON representation.</p><pre>public abstract class BaseDto {<br>    public String toJson() {<br>        try {<br>            return new ObjectMapper().writeValueAsString(this);<br>        } catch (JsonProcessingException jsonProcessingException) {<br>            return &quot;{}&quot;;<br>        }<br>    }<br>}</pre><p>Since this class is declared as abstract, it cannot be instantiated directly. Other DTO classes will extend this class and inherit the toJson() method. I just want to have JSON logs for the DTO classes. Better Stack automatically processes any JSON appended to the end of the log entry.</p><p>You may also want to create a utility class, like JsonHelper, which provides a static method for transforming any given object into a JSON string.</p><pre>public class JsonHelper {<br>    public static String toJson(Object o) {<br>        try {<br>            return new ObjectMapper().writeValueAsString(o);<br>        } catch (JsonProcessingException exception) {<br>            return &quot;{}&quot;;<br>        }<br>    }<br>}</pre><p>The UserDto:</p><pre>package com.spring.boot.dev.notes.dto;<br><br>import lombok.*;<br><br>@Getter<br>@Setter<br>@Builder<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class UserDto extends BaseDto {<br>    private Long id;<br>    private String email;<br>    private String firstName;<br>    private String lastName;<br>}</pre><h4>Implementing The Controller And Services</h4><p>PR’s:</p><ol><li><a href="https://github.com/tayfun-akguc/spring-boot-dev-notes/pull/6/files">https://github.com/tayfun-akguc/spring-boot-dev-notes/pull/6/files</a></li><li><a href="https://github.com/tayfun-akguc/spring-boot-dev-notes/pull/7">https://github.com/tayfun-akguc/spring-boot-dev-notes/pull/7</a></li></ol><p>UserController:</p><pre>@RestController<br>@RequiredArgsConstructor<br>@RequestMapping(value = &quot;api/v1/users&quot;, produces = MediaType.APPLICATION_JSON_VALUE)<br>public class UserController {<br><br>    private final UserService userService;<br><br>    @GetMapping(&quot;{id}&quot;)<br>    public ResponseEntity&lt;UserDto&gt; getUserById(@PathVariable(&quot;id&quot;) Long id) {<br>        var response = userService.getUserById(id);<br><br>        return ResponseEntity.ok()<br>                .body(response);<br>    }<br><br>}</pre><p>UserService:</p><pre>public interface UserService {<br>    UserDto getUserById(Long id);<br>}</pre><p>MockService:</p><pre>public interface MockService {<br>    void logUserId(Long id);<br>}</pre><p>UserServiceImpl:</p><pre>@Slf4j<br>@Service<br>@RequiredArgsConstructor<br>public class UserServiceImpl implements UserService {<br><br>    private final Faker faker = new Faker();<br>    private final MockService mockService;<br><br>    @Override<br>    public UserDto getUserById(Long id) {<br>        if (id == 0) {<br>            log.error(&quot;Invalid user id provided. userId: {}&quot;, id);<br>            throw new ResponseStatusException(HttpStatus.BAD_REQUEST);<br>        }<br>        if (id % 2 == 0) {<br>            log.warn(&quot;User not found. userId: {}&quot;, id);<br>            throw new ResponseStatusException(HttpStatus.NOT_FOUND);<br>        }<br>        var user = UserDto.builder()<br>                .id(id)<br>                .email(faker.internet().emailAddress())<br>                .firstName(faker.name().firstName())<br>                .lastName(faker.name().lastName())<br>                .build();<br>        log.info(&quot;User found! userId: {}{}&quot;, user.getId(), user.toJson());<br>        mockService.logUserId(id);<br>        return user;<br>    }<br>}</pre><p>MockServiceImpl:</p><pre>@Slf4j<br>@Service<br>public class MockServiceImpl implements MockService {<br>    @Override<br>    public void logUserId(Long id) {<br>        log.info(&quot;The user id: {}&quot;, id);<br>    }<br>}</pre><h4>Injecting The Logger</h4><p>I am utilizing Lombok’s @Slf4j annotation to automatically inject a static logger variable into my service classes. This simplifies logging by eliminating the need to manually declare a logger. The Slf4j annotation stands for Simple Logging Facade for Java, which acts as an abstraction layer for various logging frameworks like Logback, Log4j, java.util.logging . By using Slf4j, the application remains decoupled from any specific logging implementation.</p><p>Without using the @Slf4j annotation, you can manually create the logger in your class like this:</p><pre>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>@Service<br>@RequiredArgsConstructor<br>public class UserServiceImpl implements UserService {<br>  private static final Logger log = LoggerFactory<br>          .getLogger(UserServiceImpl.class);<br>  <br>}</pre><p>Usages examples:</p><pre>logger.trace(&quot;Trace log example!&quot;);<br>logger.debug(&quot;Debug log example!&quot;);<br>logger.info(&quot;User found with id: {} {}&quot;, user.getId(), user.toJson());<br>logger.warn(&quot;Warning log example!&quot;);<br>logger.error(&quot;Error log example!&quot;);</pre><p>Trace and debug logs will not be displayed in Better Stack, as the logging level is set to <strong>INFO </strong>in the logback.xml configuration.</p><pre>&lt;root level=&quot;INFO&quot;&gt;<br>  ...<br>&lt;/root&gt;</pre><h4>Checking The Logs</h4><p>After starting the Spring Boot application and hitting http://localhost:8080/api/v1/users/1, you will not see any logs in Live Tail because spring.profiles.defaultis set to local, and the Logtail appender is not included in the local profile. However, you should see similar logs on your console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iA1pB6COGsNIxuRq-HKLZw.png" /><figcaption>Application startup</figcaption></figure><p>Info log screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gaaVNRGA1rwOninb52KQGw.png" /><figcaption><a href="http://localhost:8080/api/v1/users/1">http://localhost:8080/api/v1/users/1</a></figcaption></figure><p>Warn log screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nXXhIVIT57kxItaN1lLYDA.png" /><figcaption><a href="http://localhost:8080/api/v1/users/2">http://localhost:8080/api/v1/users/2</a></figcaption></figure><p>Error log screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubsRHIs_oQC7_n_z1N5vSg.png" /><figcaption><a href="http://localhost:8080/api/v1/users/0">http://localhost:8080/api/v1/users/0</a></figcaption></figure><h4>Switching to Non Local Profile</h4><p>You can set the default spring profile as dev in pom.xml file spring.profiles.default: dev</p><p>Alternatively, you can specify the active profile while running the JAR file by passing the spring.profiles.active property as a command line argument.</p><pre>java -jar better-stack-logging/target/better-stack-logging-1.0-SNAPSHOT.jar --spring.profiles.active=dev</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFs9cZFn3BAlY2Bwn5k1IQ.png" /></figure><p>The logs after sending HTTP requests to users endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hae2aLP4KWN7CHTPL7_a1w.png" /><figcaption>Console Logs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aK3L2ulvXetdx4Zmd2mbvg.png" /><figcaption>Extended Info Log on BetterStack</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-Kzj8atBlmKkjYf7mVliA.png" /><figcaption>All Logs on BetterStack</figcaption></figure><h4>Querying on BetterStack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKBMY3Fx-hYuIXiWZcfmzg.png" /><figcaption>By runtime.class=”com.spring.boot.dev.notes.service.impl.UserServiceImpl” and (level:INFO OR level:WARN)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fEa9MKnBlyy4cWKCR4jaBA.png" /><figcaption>By Trace Id</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0CGvsX0WQihFXkQMHpG0FA.png" /><figcaption>By JSON property</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NRcxPQE2EEbDhwyCcv1YTg.png" /><figcaption>By JSON property</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRB5u0u3urBRwV67l1Qf_g.png" /><figcaption>By App</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAVt7jDRNnjr-7AhQBhAEQ.png" /><figcaption>By Runtime method</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJms_1n8Y79rAMl42BQGDg.png" /><figcaption>By Level</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FoK4q9M-mQlv9N4tRqiO6g.png" /><figcaption>By Level</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sg21MHrDnWnVRSWWEghlgQ.png" /><figcaption>By Level</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oxb2sOah9_PazmFYwu2TsQ.png" /><figcaption>By Class</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2f8d9edaddc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>