Spring Boot Logging Example Using SL4J (POC) - NESTED CODE || TECH FLOAT

Breaking

Post Top Ad

Post Top Ad

Tuesday, 15 March 2022

Spring Boot Logging Example Using SL4J (POC)

Today We would explain how to implement SL4J logging system into Spring boot project. A general question what is the benefit to use SL4J over Log4J- Answer is simple, since, when we pass any parameter into log4j log.debug method, parameter needs to be string concatenated. Hence, a separate memory allocation is needed in this case. However, SL4J does not demand to pass the parameter as string concatenation- here as a method variable new param value could be passed. We will see the same in below example.


Step-1: Lets create a new project for this POC - from all of our favorite spring initializer https://start.spring.io/ where in general spring web and devtool dependency has been added.


Step-2: Post importing the project to the eclipse, lets create a controller like below example.


package com.ncteam.loggingexample;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RestController;


@SpringBootApplication

@RestController

public class LoggingExampleApplication {

//logger object needs to be created- make sure you are importing package SL4j

Logger log = LoggerFactory.getLogger(LoggingExampleApplication.class);


public static void main(String[] args) {

SpringApplication.run(LoggingExampleApplication.class, args);

}

@GetMapping("/user/{name}")

public String getName(@PathVariable String name){

//to capture the log in debug mode to understand the request

log.debug("Request for user--> {}", name);

if (name.equalsIgnoreCase("test")){

log.error("Response for the API endpoint Null pointer exception");

throw new NullPointerException();

}

String returnVAl = "Hello, "+name+" Welcome to the NC Team Blog!!";

                ////to capture the log in debug mode to understand the response

log.debug("Response for the API endpoint--> {}", returnVAl);

return returnVAl;

}

}


Step-3: Make sure to add logback-spring.xml under resources folder. Below is the sample , make sure 

you are replacing the below highlighted base package as per your project sturcture and also change the log file path accordingly.

 <?xml version="1.0" encoding="UTF-8"?>

<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">

        <encoder>

            <pattern>[%-5level] %d{dd-MM-yyyy hh:mm:ss.SSS a} [%thread]  %logger{50} - %msg%n</pattern>

        </encoder>

    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">

        <file>C:/Abhik/LogFile1/nc-app.log</file>

        <encoder>

            <pattern>[%-5level] %d{dd-MM-yyyy hh:mm:ss.SSS a} [%thread]  %logger{50} - %msg%n</pattern>

        </encoder>

    </appender>

    <root level="ERROR">

        <appender-ref ref="STDOUT" />

    </root>

    <logger name="com.ncteam.loggingexample" level="ALL" additivity="true">

        <appender-ref ref="FILE"/>

    </logger>

</configuration>

  Step-4: That's it, now execute the project and you could see the log file got generated in the path mentioned in the xml file. Also if you hit the end point url, logs will get generated accordingly - based on mode type - debug/error etc. 

No comments:

Post a Comment

Post Bottom Ad