Reader small image

You're reading from  Spring Boot and Angular

Product typeBook
Published inDec 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781803243214
Edition1st Edition
Languages
Right arrow
Authors (2):
Devlin Basilan Duldulao
Devlin Basilan Duldulao
author image
Devlin Basilan Duldulao

Devlin Basilan Duldulao is a full-stack engineer with over 8 years of web, mobile, and cloud development experience. He has been a recipient of Microsoft's Most Valuable Professional (MVP) award since 2018 and earned the title of Auth0 Ambassador for his passion for sharing best practices in application security. Devlin has passed some prestigious software and cloud development exams, such as MSCD, Azure Associate Developer, AWS Associate Developer, and Terraform Associate. He has also authored the book ASP.NET Core and Vue.js and coauthored the book Practical Enterprise React in 2020 and 2021, amid the pandemic.
Read more about Devlin Basilan Duldulao

Seiji Ralph Villafranca
Seiji Ralph Villafranca
author image
Seiji Ralph Villafranca

Seiji Ralph Villafranca graduated Cum Laude with a degree of Bachelor of Science In Computer Science at University of Santo Tomas in the Philippines. He has 6 years of experience in Web and Mobile Development and has also earned the title of Auth0 Ambassador for having passions in application securities, He holds several certifications in Angular Development from Beginner to Expert Level. Seiji is also one of the Community Leaders of Angular Philippines which is the largest Angular group in the Philippines, the community has lead him to speak in different meetups of tech communities, workshops and even local and international conferences, he is enthusiastic in sharing knowledge in coding, organizing events and meetups for the community as well as writing content for students and professionals. He also has been a mentor in several hackathons as he loves the startup community. Seiji loves to develop new projects that are on web or mobile, he is currently a senior software engineer in a company based in Malaysia, He is not just a coder but also a mentor, teacher and trainer for students, professionals and companies.
Read more about Seiji Ralph Villafranca

View More author details
Right arrow

Logging Events in Spring Boot

In the previous chapter, we discussed the ideas, features, and implementation of Cross-Origin Resource Sharing (CORS) in securing our application. We also learned about JSON Web Tokens (JWTs) and how to generate one by creating authentication endpoints.

This chapter will focus on logging events in our Spring Boot application. We will discuss the popular packages for logging in to and configuring Spring Boot, where to save them, and what to do with logs as we develop our application.

In this chapter, we will cover the following topics:

  • Getting started with SLF4J and Log4j2
  • Setting up SLF4J and Log4j2
  • Using logs

Technical requirements

The finished version of this chapter’s code may be seen at the following link: https://github.com/PacktPublishing/Spring-Boot-and-Angular/tree/main/Chapter-08/superheroes.

Getting started with SLF4J and Log4j2

Logging is considered one of the most important aspects of developing an application. Its importance tends to be underrated and, worse, we forget to apply it to our applications.

Event logging is used in most tech industries, especially those providing enterprise applications. It is applied with a given standard to prevent complex debugging and allow for an easier understanding of the code we are reading. A well-written and structured log can benefit developers, especially when maintaining or debugging code from another developer. Instead of searching exhaustively for an error, records will expedite the debugging process, providing information on where and why the error occurred, and what has happened in our application.

Logging has also evolved with improvements in languages and frameworks; in backend development, several logging frameworks have been developed to provide more flexible logging capabilities. Some of the example frameworks...

Logging using SLF4J

One of the popular logging frameworks being used with Java is Simple Logging Façade for Java, or SLF4J. It is one of the most widely used frameworks since it allows users to use any logging frameworks, such as Log4j, Logback, the java.util.logging package, or Java’s own logging engine, JUL, using only a single dependency. This means that we can switch from one logging framework to another depending on what is needed.

There are several advantages to using SLF4J:

  • SLF4J enables us to switch from one framework to another at runtime or deployment.
  • SLF4J has a migrator tool that allows us to migrate existing projects using the Java Class Library from Log4j to SLF4J.
  • SLF4J supports parameterized logging messages to bind dynamic values for our logs.
  • SLF4J decouples the application from the logging framework. We do not need to worry about which logging framework is being used when developing our application.

Methods and classes of...

Logging using Log4j2

Log4j2 is one of the most common logging frameworks used with Java. Since SLF4J is an abstraction of logging frameworks, Log4j2 can be used with SLF4J. Log4j2 is very flexible and offers different ways to store log information for debugging; it also supports asynchronous logging and displays logs with a severity level to quickly identify the importance of messages.

Let’s discuss the following features of Log4j2:

  • The Log4j2 Logger
  • Log4j2 Appenders
  • Log4j2 Layouts
  • Log4j2 Markers
  • Log4j2 Filters

The Log4j2 Logger

The Logger is the main feature used by our application to create LogRecord instances. This means the logger is responsible for dispatching the messages. To create a Log4j2 Logger, we only need the following code:

Logger log = LogManager.getLogger(ExampleClass.class);

After creating a new Logger, we can now use it to call several methods, such as info(), to dispatch messages.

Log4j2 Appenders

Appenders...

Setting up SLF4J and Log4j2

We will now implement several logging frameworks, including Logback and Log4j2, in our Spring Boot application. Remember that SLF4J is already included.

Configuring Logback

Logback is the default logger used by Spring Applications, so no dependencies need to be installed to use it. The spring-boot-starter-logging dependency is already included once we create our Spring Boot application. The first step we need to take is to make our Logback configuration file.

In our project, under the resources folder, we will add the logback-spring.xml file. This is where we will place our Logback configuration. The following is an example configuration:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <property name="LOGS" value="./logs" />
    <!—Please refer to the logback-spring.xml of
       the GitHub...

Using logs

We can now use the log frameworks we have configured in our Spring Boot application to define logs on the different parts of our code. To do so, we must first create a new logger instance.

An example would be creating a log when a user attempts to get a list of all anti-heroes. In AntiHeroeController, we will add the following code to create a new logger instance:

private static final Logger LOGGER = LoggerFactory.getLogger(AntiHeroController.class);

We must also be aware that LoggerFactory and Logger should be under the SLF4J dependency. It is always recommended to use SLF4J as this is an abstraction of logging frameworks and makes it easier to switch between them.

In this case, our import should be as follows:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Once we have created a new logger instance, we can now use it in our methods, for example, if we want to display a log when the user attempts to get a list of anti-heroes.

To accomplish...

Summary

This chapter has explained the concept and importance of loggers and how they can help developers in debugging and maintaining applications. It has introduced Log4j2, a third-party framework for Spring Boot that offers several features, such as Appenders, Filters, and Markers, which can assist in categorizing and formatting log events for developers. It has also introduced the concept of SLF4J, which is an abstraction of logging frameworks that allows us to switch between different frameworks at runtime or deployment.

In the following chapter, we will learn about the concepts and integration of unit testing in our Spring Boot application.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Spring Boot and Angular
Published in: Dec 2022Publisher: PacktISBN-13: 9781803243214
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Devlin Basilan Duldulao

Devlin Basilan Duldulao is a full-stack engineer with over 8 years of web, mobile, and cloud development experience. He has been a recipient of Microsoft's Most Valuable Professional (MVP) award since 2018 and earned the title of Auth0 Ambassador for his passion for sharing best practices in application security. Devlin has passed some prestigious software and cloud development exams, such as MSCD, Azure Associate Developer, AWS Associate Developer, and Terraform Associate. He has also authored the book ASP.NET Core and Vue.js and coauthored the book Practical Enterprise React in 2020 and 2021, amid the pandemic.
Read more about Devlin Basilan Duldulao

author image
Seiji Ralph Villafranca

Seiji Ralph Villafranca graduated Cum Laude with a degree of Bachelor of Science In Computer Science at University of Santo Tomas in the Philippines. He has 6 years of experience in Web and Mobile Development and has also earned the title of Auth0 Ambassador for having passions in application securities, He holds several certifications in Angular Development from Beginner to Expert Level. Seiji is also one of the Community Leaders of Angular Philippines which is the largest Angular group in the Philippines, the community has lead him to speak in different meetups of tech communities, workshops and even local and international conferences, he is enthusiastic in sharing knowledge in coding, organizing events and meetups for the community as well as writing content for students and professionals. He also has been a mentor in several hackathons as he loves the startup community. Seiji loves to develop new projects that are on web or mobile, he is currently a senior software engineer in a company based in Malaysia, He is not just a coder but also a mentor, teacher and trainer for students, professionals and companies.
Read more about Seiji Ralph Villafranca