Spring boot

Spring boot logging example

SLF4J instead of Spring boot default logging

Spring Boot uses Commons Logging for all internal logging but leaves the underlying log implementation open.

By default, if you use the “Starters”, Logback is used for logging.

spring-boot-starter-web artifact comes with Slf4j and Logback, there is no need for adding any additional dependency. So there will not be any change in pom.xml

Configuring (pom.xml)

<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 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.4.RELEASE</version>
		<relativePath />
		<!-- lookup parent from repository -->
	</parent>
	<groupId>com.candidjava</groupId>
	<artifactId>spring</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>
	<build>
		<finalName>springBoot</finalName>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

Spring boot logging to file

By default, Spring Boot logs only to the console and does not write log files. If you want to write log files in addition to the console output, you need to set a property in your application.properties or application.yaml.

logging.file.name=student.log

logging.file.path=d:/log

or in YAML format as below code

application.yml

spring:
logging:
  file: log/student.log
  pattern:
    console: "%d %-5level %logger : %msg%n"
    file: "%d %-5level [%thread] %logger : %msg%n"
  level:
    com.candidjava.*: INFO

Spring boot LOG levels

ERROR, WARN, INFO, DEBUG, or TRACE

Launch and Test Logging (LoggingApplication.java)

package com.candidjava.springboot;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class LoggingApplication {
 private static final Logger logger = LoggerFactory.getLogger(LoggingApplication.class);

 public static void main(String[] args) {
  SpringApplication.run(LoggingApplication.class, args);
  logger.info("This is a info message");
  logger.debug("This is a debug message");
  logger.warn("This is a warn message");
  logger.error("This is a error message");
 }
}

Sample Controller (StudentController.java)

package com.candidjava.springboot.controller;

import java.util.List;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.candidjava.springboot.LoggingApplication;
import com.candidjava.springboot.models.Student;
import com.candidjava.springboot.service.StudentService;

@RestController
@RequestMapping(value = "/student")
public class StudentController {
 private static final Logger logger = LoggerFactory.getLogger(LoggingApplication.class);
 @Autowired
 StudentService service;

 @PostMapping("/create")
 public void create(@Valid @RequestBody Student student) {
  logger.info("Creating a Student");
  service.createStudent(student);
 }

 @GetMapping("/getAll")
 public List<Student> get() {
  logger.info("getting All Students");
  return service.getAllStudents();
 }

 @GetMapping("/get/{id}")
 public Student getById(@PathVariable("id") String id) {
  logger.info("getting the Student, Id:" + id);
  return service.getStudentById(id);
 }

 @PutMapping("/update/{id}")
 public void update(@PathVariable("id") String id, @Valid @RequestBody Student student) {
  logger.info("updating the Student, Id:" + id);
  service.updateStudent(id, student);
 }

 @DeleteMapping("/delete/{id}")
 public void deleteById(@PathVariable("id") String id) {
  logger.info("deleting the Student, Id:" + id);
  this.service.deleteStudentById(id);
 }

}

StudentService.java

package com.candidjava.springboot.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
import com.candidjava.springboot.models.Student;
import com.candidjava.springboot.service.StudentService;

@Service
public class StudentService {

 private List<Student> studentList = new ArrayList<Student> (Arrays.asList(

  new Student("1", "ram", "20"), new Student("2", "arun", "21"), new Student("3", "karthick", "22")

 ));

 public void createStudent(Student student) {
  studentList.add(student);
 }

 public List<Student> getAllStudents() {
  return studentList;

 }

 public Student getStudentById(String id) {
  return studentList.stream().filter(student -> student.getId().equals(id)).findFirst().get();

 }

 public void updateStudent(String id, Student student) {
  int counter = 0;
  for (Student eachStudent: studentList) {
   if (eachStudent.getId().equals(id)) {
    studentList.set(counter, student);
   }
   counter++;
  }
 }

 public void deleteStudentById(String id) {
  studentList.removeIf(student -> student.getId().equals(id));
 }

}

Student.java

package com.candidjava.springboot.models;

public class Student {
 private String id;
 private String name;
 private String age;

 public Student(String id, String name, String age) {
  this.id = id;
  this.name = name;
  this.age = age;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getAge() {
  return age;
 }

 public void setAge(String age) {
  this.age = age;
 }

}

Download source code

You can download source code from my github account (Click here)