How to improve your logging by using Spring Aspect-oriented programming (AOP)!

How to improve your logging by using Spring Aspect-oriented programming (AOP)!

Introduction

AOP is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns.?It does this by adding additional behavior to existing code without modifying the code itself.

Instead, we can declare the new code and the new behaviors separately.

Spring's?AOP framework?helps us implement these cross-cutting concerns.

Basic concepts briefly

For instance, we have an application that contains modules with some business logic.

No alt text provided for this image

But we need to add some handling of our results. Let’s take logging for example. Usually, we’d inject additional code at the end of every module.

No alt text provided for this image

Some shared functionality like logging is called?cross-cutting concern. Here are a few sources?(#1,?#2).

But we’d like to use the AOP approach and separate our logging from business logic.

No alt text provided for this image

Our new logging module will catch the output of other business modules in?join points?— points during the execution of a program, such as the execution of a method or the handling of an exception.

No alt text provided for this image

To embed logging, we unify our joinpoints into?pointcut. For this, in Spring we use the expression language.

No alt text provided for this image

For this, we use?advices —?actions at a particular?Joinpoint.

Types of advice:

  • Before?— before method execution;
  • After?— after method execution;
  • After returning?— after method returning;
  • After throwing?— after method throwing an exception;
  • After finally?— after method executing “finally” block;
  • Around?— allows us to add some preprocessing, postprocessing, or even bypass method execution.

No alt text provided for this image

To see the sample spring boot project you can see the full code on my GitHub :

In this example, we'll see how to use AspectJ (aop advice) to measure method execution time as a logging mechanism in Spring Boot applications to handle cross-cutting problems.

Let's start developing the Spring Boot application with AOP.

https://github.com/omarismail95/spring-aop-logging

Happy coding & learning!

Me?ssa B.C Mbaye

Software & DevOps Engineer (4x Kubernetes Certified) || FullStack Developer || IT Consultant || CyberSecurity and DevSecOps Enthusiast

2 年

要查看或添加评论,请登录

Omar Ismail的更多文章

社区洞察

其他会员也浏览了