Logging Fundamentals

File logging writes application log messages to a file on disk instead of only showing them in the console. Console output disappears when the app restarts or the terminal closes, but a log file persists and can be searched later. In Spring Boot you enable it with logging.file.name or logging.file.path in application.properties. A rolling policy splits the log into dated or size-limited files and deletes old ones, so the disk never fills up.

Features

  • One property (logging.file.name) starts writing logs to a file
  • Logs survive application restarts, since new lines are appended
  • Separate pattern for the file and the console (logging.pattern.file, logging.pattern.console)
  • Automatic rolling by size and date
  • Compressed archives (.gz) to save disk space
  • Automatic cleanup with max-history (days) and total-size-cap (total size)
  • Works with all log levels and per-package levels from 13.2

Hands-on Experiment: Creating a spring boot application to understand REST resources, HTTP methods, status codes, and request-response 

The following steps are involved in developing this hands-on experiment.

Step 1: Generate the Project

Step 2: Project Structure

Step 3: pom.xml

Step 4: application.properties

Step 5: Create Entity Class

Step 6: Create Repository Interface

Step 7: Create Service Class

Step 8: Create Controller Class

Step 9: Main Application Class

Step 10: Run the Main Application Class

Step 1: Configure the Project on Spring Initializr

Go to start.spring.io and set:

  • Project: Maven
  • Language: Java
  • Spring Boot version: 3.2.x
  • Group: com.example
  • Artifact: filelogging
  • Name: filelogging
  • Package name: com.example.filelogging
  • Packaging: Jar
  • Java: 17
  • Dependencies: Spring Web, Spring Data JPA, MySQL Driver.

Click Generate to download the ZIP, then extract and import it into your IDE as a Maven project.

Step 2: Generated Project Structure

Step 3: Explore pom.xml

<?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>3.2.5</version>
        <relativePath/>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>student-logging-demo</artifactId>
    <version>1.0.0</version>
    <name>student-logging-demo</name>
    <description>Logging Fundamentals - Student CRUD with log statements</description>

    <properties>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <!-- spring-boot-starter-web already includes SLF4J + Logback -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

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

Step 4: application.properties

spring.application.name=student-logging-demo

# ---------- MySQL ----------
# Create the database first:  CREATE DATABASE student_logging_db;
spring.datasource.url=jdbc:mysql://localhost:3306/student_logging_db
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
server.port=8082

# ---------- Logging ----------
# Default level for everything (Spring, Hibernate, Tomcat...)
logging.level.root=INFO
# Our own code logs from DEBUG upward
logging.level.com.example.logging=DEBUG
# Show the SQL that Hibernate runs (DEBUG) - useful while troubleshooting
logging.level.org.hibernate.SQL=DEBUG

# Console format: time | level | thread | logger | message
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} | %-5level | %thread | %logger{36} | %msg%n

# Also write logs to a file (created in the project folder)
logging.file.name=logs/student-app.log
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} | %-5level | %logger{36} | %msg%nCode language: PHP (php)

Step 5: Create Entity Class

package com.example.logging.entity;

import jakarta.persistence.*;

@Entity
@Table(name = "students")
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false, unique = true)
    private String email;

    private String course;

    public Student() {
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

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

    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }

    public String getCourse() { return course; }
    public void setCourse(String course) { this.course = course; }
}

Step 6: Create below Repository Interface

package com.example.logging.repository;

import com.example.logging.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {

    boolean existsByEmail(String email);
}

Step 7: Create below Service class

package com.example.logging.service;

import com.example.logging.entity.Student;
import com.example.logging.repository.StudentRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentService {

    // One logger per class - the class name appears in every log line
    private static final Logger log = LoggerFactory.getLogger(StudentService.class);

    private final StudentRepository studentRepository;

    public StudentService(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    public Student create(Student student) {
        log.info("Creating student with email={}", student.getEmail());

        if (studentRepository.existsByEmail(student.getEmail())) {
            log.warn("Create rejected - email already exists: {}", student.getEmail());
            throw new IllegalArgumentException("Email already registered: " + student.getEmail());
        }

        try {
            Student saved = studentRepository.save(student);
            log.info("Student created successfully with id={}", saved.getId());
            log.debug("Saved student details: name={}, course={}", saved.getName(), saved.getCourse());
            return saved;
        } catch (Exception ex) {
            // Pass the exception as the LAST argument to log the full stack trace
            log.error("Failed to create student with email={}", student.getEmail(), ex);
            throw ex;
        }
    }

    public List<Student> getAll() {
        log.info("Fetching all students");
        List<Student> students = studentRepository.findAll();
        log.debug("Total students found: {}", students.size());
        return students;
    }

    public Student getById(Long id) {
        log.info("Fetching student with id={}", id);
        return studentRepository.findById(id).orElseThrow(() -> {
            log.warn("Student not found with id={}", id);
            return new IllegalArgumentException("Student not found: " + id);
        });
    }

    public Student update(Long id, Student updated) {
        log.info("Updating student with id={}", id);
        Student existing = getById(id);

        log.debug("Before update: name={}, course={}", existing.getName(), existing.getCourse());
        existing.setName(updated.getName());
        existing.setEmail(updated.getEmail());
        existing.setCourse(updated.getCourse());

        Student saved = studentRepository.save(existing);
        log.info("Student updated successfully with id={}", saved.getId());
        log.debug("After update: name={}, course={}", saved.getName(), saved.getCourse());
        return saved;
    }

    public void delete(Long id) {
        log.info("Deleting student with id={}", id);
        if (!studentRepository.existsById(id)) {
            log.warn("Delete failed - student not found with id={}", id);
            throw new IllegalArgumentException("Student not found: " + id);
        }
        studentRepository.deleteById(id);
        log.info("Student deleted successfully with id={}", id);
    }
}

Step 8: Create Controller class

package com.example.logging.controller;

import com.example.logging.entity.Student;
import com.example.logging.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/students")
public class StudentController {

    private static final Logger log = LoggerFactory.getLogger(StudentController.class);

    private final StudentService studentService;

    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    @PostMapping
    public ResponseEntity<?> create(@RequestBody Student student) {
        log.info("POST /students called");
        try {
            return ResponseEntity.status(HttpStatus.CREATED).body(studentService.create(student));
        } catch (IllegalArgumentException ex) {
            return ResponseEntity.badRequest().body(Map.of("error", ex.getMessage()));
        }
    }

    @GetMapping
    public List<Student> getAll() {
        log.info("GET /students called");
        return studentService.getAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getById(@PathVariable Long id) {
        log.info("GET /students/{} called", id);
        try {
            return ResponseEntity.ok(studentService.getById(id));
        } catch (IllegalArgumentException ex) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", ex.getMessage()));
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> update(@PathVariable Long id, @RequestBody Student student) {
        log.info("PUT /students/{} called", id);
        try {
            return ResponseEntity.ok(studentService.update(id, student));
        } catch (IllegalArgumentException ex) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", ex.getMessage()));
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(@PathVariable Long id) {
        log.info("DELETE /students/{} called", id);
        try {
            studentService.delete(id);
            return ResponseEntity.ok(Map.of("message", "Student deleted: " + id));
        } catch (IllegalArgumentException ex) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", ex.getMessage()));
        }
    }
}

Step 9: Main Application

package com.example.logging;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class LoggingApplication {

    public static void main(String[] args) {
        SpringApplication.run(LoggingApplication.class, args);
    }
}

Step 10: Run the LoggingApplication

Scroll to Top