DEV Community

sanjay shivanna
sanjay shivanna

Posted on

Spring boot : Rest project with lomback and logback

A simple spring boot REST example with lomback and logback configuration for logging
Pom.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.sanjay.springrest</groupId>
    <artifactId>spring-rest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-rest</name>
    <description>Demo project for Spring Boot rest services</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Rest Controller class

package com.sanjay.springrest.springrest.rest;

import com.sanjay.springrest.springrest.model.Users;
import com.sanjay.springrest.springrest.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/users")
public class LoginController {

    @Autowired
    LoginService loginService;

    @GetMapping("/all")
    public ResponseEntity getAllUsers() {
        log.debug("Inside GetAll users");
        return new ResponseEntity(loginService.getAllUsers(), HttpStatus.OK);
    }

    @PostMapping()
    public ResponseEntity addUsers(@RequestBody Users user) {
        log.debug("Inside add all users");
        loginService.addUser(user.getEmail(), user.getPassword());
        return new ResponseEntity(HttpStatus.CREATED);
    }

    @GetMapping()
    public ResponseEntity getUser(@RequestParam String email) {
        log.debug("Inside Get user {}", email);
        return new ResponseEntity(loginService.getUser(email), HttpStatus.OK);
    }

    @DeleteMapping
    public ResponseEntity deleteUser(@RequestParam("emailId") String email) {
        log.debug("Delete user {}", email);
        loginService.deleteUser(email);
        return new ResponseEntity(HttpStatus.OK);
    }


}

Service class

package com.sanjay.springrest.springrest.service;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class LoginService {

    HashMap<String, String> users = new HashMap<>();

    public void addUser(String email, String password) {
        users.put(email, password);
    }

    public void deleteUser(String email) {
        users.remove(email);
    }

    public List<String> getAllUsers() {
        return new ArrayList<>(users.keySet());
    }

    public String getUser(String email) {
        return users.get(email);
    }

}

Model class with lombock

package com.sanjay.springrest.springrest.model;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;

@Data
public class Users {
    String email;
    String password;

}

logback-spring.xml configuration file

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

    <property name="LOGS" value="./logs" />

    <appender name="Console"
              class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable
            </Pattern>
        </layout>
    </appender>

    <appender name="RollingFile"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOGS}/spring-boot-logger.log</file>
        <encoder
                class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
        </encoder>

        <rollingPolicy
                class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- rollover daily and when the file reaches 10 MegaBytes -->
            <fileNamePattern>${LOGS}/archived/spring-boot-logger-%d{yyyy-MM-dd}.%i.log
            </fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>

    <!-- LOG everything at INFO level -->
    <root level="info">
        <appender-ref ref="RollingFile" />
        <appender-ref ref="Console" />
    </root>

    <!-- LOG "com.sanjay*" at TRACE level -->
    <logger name="com.sanjay" level="trace" additivity="false">
        <appender-ref ref="RollingFile" />
        <appender-ref ref="Console" />
    </logger>

</configuration>

Project structure
Alt Text

Github link for complete project
https://github.com/sanjaybsm/spring-rest

Top comments (0)