(/) REFCARDS (/REFCARDZ)
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS) (/users/login.html)
Culture and Methodologies Data Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance
(/culture-and-methodologies) (/data-engineering) (/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)
The software you build is only as secure as the code
that powers it. Learn how malicious code creeps into
your software supply chain.
⌛ Save Your Seat
(https://web.cvent.com/hub/events/76ac3891-a39e-
45ef-b154-01cdf152ddce/landing?
utm_campaign=JFrog&utm_medium=Dzone%2520Web&utm_source=Announcements)
RELATED
Magic of Aspects: How AOP Works in Spring (/articles/magic-of-aspects-how-aop-works-in-spring)
Comprehensive Guide to Unit Testing Spring AOP Aspects (/articles/comprehensive-guide-to-unit-testing-spring-aop-asp)
How to Merge HTML Documents in Java (/articles/how-to-merge-html-documents-in-java)
The Future of Java and AI: Coding in 2025 (/articles/the-future-of-java-and-ai-coding-in-2025)
Partner Resources
Video Library Video Library
Access On-Demand Webinars, Fireside Chats, and Access On-Demand Webinars, Fireside Chats, and
Roundtables in our video library. Click Here ► Roundtables in our video library. Click Here ►
Presented by DZone Presented by DZone
×
(/) REFCARDS (/REFCARDZ)
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS) (/users/login.html)
Culture and Methodologies Data Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance
(/culture-and-methodologies) (/data-engineering) (/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)
×
DZone (https://dzone.com) (/)
REFCARDS (/REFCARDZ)
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS)
/ Coding (https://dzone.com/coding) / Java (https://dzone.com/java) / Adding Versatility to Java Logging Aspect
(/users/login.html)
Adding Versatility to Java Logging Aspect
Culture and Methodologies
(/culture-and-methodologies)
Data Engineering
(/data-engineering)
Software Design and Architecture
(/software-design-and-architecture)
Coding
(/coding)
Testing, Deployment, and Maintenance
(/testing-deployment-and-maintenance)
Logging on a method or methods of a class becomes dynamically woven. This article deep dives
and illustrates how a logging aspect may be boosted to make the most of it.
By Soham Sengupta (/users/5062469/sohampayback.html) · Jan. 10, 24 · Tutorial
Likes (1) Comment (0) Save Tweet Share 3.7K Views
Logging (https://dzone.com/articles/logging-best-practices) plays a key role in software development,
helping troubleshoot live applications. Log messages, therefore, need special attention and be curated
to be clearly made out.
A large enterprise application usually hosts different types of logging strategies and may not log every
single, relatively unimportant message in a production environment, unlike in a development
environment. This helps save storage and boosts performance. Purging older logs follows
organizational policy, and logging comes at the cost of performance, though we may not apparently feel
the latency of milliseconds on lower environments catering to much less load than on the production.
Like code and documentation, logging itself is often boilerplate and manual and thus prone to human
errors. To avoid human errors, such as the omission of a log message, or to get rid of boilerplates, we
often resort to using Aspects in Java applications. Logging on a method or methods of a class becomes
dynamically woven. This article deep dives and illustrates how a logging aspect may be boosted to
make the most of it.
×
Brief About Using Aspect in Logging
g p gg g
Let us look at the code snippet in
(/) REFCARDS [Listing-1]
(/REFCARDZ) showing
TREND REPORTS
log method execution time and metrics:
a traditional
(/TRENDREPORTS)
EVENTS good old approach (/users/login.html)
(/EVENTS) of using SLF4J to
Culture and Methodologies Data Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance
Java
(/culture-and-methodologies) (/data-engineering) (/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)
1 public void someMethod(String arg0, String arg1, int arg2) {
2 long ts=System.currentTimeMillis();
3 log.debug("someMethod invoked : arg0: {} arg1: {} arg2: {}",arg0,arg1,arg2);
4 // business operations
5 // ...
6 //.......
7 log.debug("someMethod returns. Took {} millseconds",(System.currentTimeMillis()-ts));
8 }
[Listing-1]
The above code snippet, however, uses generalized methods and parameter names.
The log object may be obtained via any of the following without loss of generality:
1. Logger logger=Logger.getLogger("logger-1"); // For Java 8 or lower versions // without third-party
dependencies
2. java.lang.System.Logger logger=System.getLogger("sysloger"); // Java 9 or // higher with or without
third-party dependencies
3. Using SLF4j implementation such as Log4j/Log4j2 / Logback, etc., directly or indirectly, such as by
using my favorite Lombok annotation that generates the code via APT. @Slf4j
The approach, regardless of how and what we create as a log object, remains the same.
This approach has the following pitfalls: they are manual and hence prone to error and are, of course,
boilerplates,
× which Aspects help mitigate. Aspects are instrumented triggers that may be used with or
ith t th S i (htt //d / ti l / h t i i 1) f k th hA t
without the Spring (https://dzone.com/articles/what-is-spring-aop-1) framework, though Aspect
Oriented ProgrammingREFCARDS
(/) (/REFCARDZ)
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS)
(https://dzone.com/articles/an-introduction-aspect-oriente) often infers usage of
(/users/login.html)
the latter. This article, however,
Culture and Methodologies
uses Spring
Data Engineering
Aspect throughout and Coding
Software Design and Architecture
including the example we are going
Testing, Deployment, and Maintenance
to(/culture-and-methodologies)
revisit shortly on how(/data-engineering)
a Logging Aspect(/software-design-and-architecture) [Listing-1].(/testing-deployment-and-maintenance)
might have been used in (/coding)
We create a custom annotation and an Aspect that triggers around the methods annotated with it.
Java
1 @Documented
2 @Retention(RUNTIME)
3 @Target(ElementType.METHOD)
4 public @interface LogExecutionTime {
5 }
6
7
8
9 @Component
10 @Aspect
11 @Slf4j
12 public class LoggingAspect {
13
14
15 @Around("@annotation(com.somecompany.pkg.annotation.LogExecutionTime)")
16 public Object aroundMethodExecution(ProceedingJoinPoint joinPoint) throws Throwable {
17 long start = System.currentTimeMillis();
18
19 Object result = joinPoint.proceed();
20 long executionTime = System.currentTimeMillis() - start;
21 log.info("{} took {} milliseconds to execute",jointPoint.getSignature().getName(),executionTime);
22 }
23 return result;
24 }
[Listing-2]
×
The aspect logs the execution time of methods along with their names Nothing new hitherto has been
The aspect logs the execution time of methods along with their names. Nothing new hitherto has been
discussed, and the assumption (/) REFCARDS (/REFCARDZ)
hasTREND
been that
REPORTSthe (/TRENDREPORTS)
audience
EVENTSis
aware of the Spring framework,
(/EVENTS) custom
(/users/login.html)
annotation, and aspects. Data
Culture and Methodologies
Should one require
Engineering
a quick reference or revision,
Software Design and Architecture Coding
any Testing,
studyDeployment,
material,and Maintenance
including official documentation
(/culture-and-methodologies) of Spring
(/data-engineering) and Java, may be referred
(/software-design-and-architecture) to. The next
(/coding) section is dedicated to
(/testing-deployment-and-maintenance)
an approach we have used and benefited from and that we use across different projects as good as a
library.
Adding Sophisticated Features to the Logging Aspect
We added to add sophisticated features to our logging aspect as we were not content with just method
execution time. We wanted to have log levels in the aspect. As we discussed earlier in the chapter,
LEVEL plays a crucial role in logging. Having the ability to switch log level is, therefore, indispensable.
Also, having provision to log method parameters and return value, if one, would have been fine-
grained.
While loggers come with their respective conversion patterns, such as log4j, which offers an XML-based
approach to configure almost everything and not just the Conversion Pattern and Layout of Appenders,
it’s worth noting that some projects are designed to follow a pre-defined message pattern regardless of
the configuration. The reason for doing so may be to not blindly rely on a configuration and chance
losing the usual search patterns. An organization may wish to have all the microservices it owns log a
message like “ className ## methodName ## logMessage .” We wanted the conversion pattern, too,
to be customizable in the logging aspect.
The code snippet in [Listing-3] shows an enhanced version of the annotation LoggingAspect :
Java
1 @Retention(RUNTIME)
2 @Target(ElementType.METHOD)
3 public @interface LogExecution {
4
×5 public Class<? extends LogFormatter> formatter() default LogFormatter.class;
bli i l l d f l i f
6
7
8
public String level() default "info";
public boolean(/)logResult()
REFCARDSdefault false;
(/REFCARDZ)
TREND
public boolean logParams() default false;
REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS) (/users/login.html)
9
Culture and Methodologies Data Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance
10 }
(/culture-and-methodologies) (/data-engineering) (/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)
11
12 // The LogFormatter class looks like this:
13
14 public class LogFormatter {
15 public String format(MethodSignature methodSignature ,Object result) {
16 return String.valueOf(methodSignature.getDeclaringTypeName()+" :: "+methodSignature.getName()+"[] :: "+ resu
17 }
18 }
[Lisiting-3]
Using the Logging Aspect
Java
1 @LogExecution(logResult = true,level ="info",logParams = true,formatter = SimpleLogFormatter.class)
2
3 public Object someMethod(String x,int y) {
4 try {
5 TimeUnit.SECONDS.sleep(3); // Intentional, NoOp delay
6 } catch (InterruptedException e) {
7 }
8 return "x = "+x+" y= "+y+" Now it's "+LocalDateTime.now();
9 }
10
11
12 public class SimpleLogFormatter extends LogFormatter {
13
14 @Override
15 public String format(MethodSignature methodSignature, Object result){
16
17 return methodSignature.getName()+"---->"+result;
×
18 }
19
20 } (/) REFCARDS (/REFCARDZ)
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS) (/users/login.html)
Culture and Methodologies Data Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance
(/culture-and-methodologies) (/data-engineering) (/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)
[Listing-4]
So, we pass the following to it:
1. Whether to log the method’s return value
2. Level of the log
3. Whether to log parameters passed to the method
4. And finally, a transformer Class, which subclasses the LogFormatter
This is a sample log of the above method:
024-01-10 01:09:27.971[0;39m [32m INFO[0;39m [35m12904[0;39m [2m---[0;39m [2m[nio-8080-
exec-1][0;39m [36mio.spb.ordered.a.aspect.LoggingAspect [0;39m [2m:[0;39m someMethod----
>x = John y= Doe Now it’s 2024-01-10T01:09:27.961848100
We can update the formatting by providing a relevant sub-class of LogFromatter and using it as the
formatter.
Finally, we can keep on adding features and make it more and more sophisticated. However, the full
source code is provided here so that readers may jointly take it ahead.
Aspect (Computer Programming) Java (Programming Language) Aspect-Oriented Programming
Opinions expressed by DZone contributors are their own.
×
RELATED
RELATED
(/) REFCARDS (/REFCARDZ)
Magic of Aspects: How AOP Works in Spring
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS) (/users/login.html)
Culture and Methodologies Data Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance
(/culture-and-methodologies)
Comprehensive (/data-engineering)
Guide to Unit Testing (/software-design-and-architecture)
Spring AOP Aspects (/coding) (/testing-deployment-and-maintenance)
How to Merge HTML Documents in Java
The Future of Java and AI: Coding in 2025
Events
Discover upcoming and on-demand webinars, fireside chats,
and virtual roundtables by industry leaders. Learn More ►
Presented by DZone
ABOUT US
About DZone (/pages/about)
ADVERTISE
Advertise with DZone Let's be friends:
Support and feedback (https://advertise.dzone.com)
(/pages/feeds)
(https://twitter.com/DZoneInc)
(https://www.facebook.com
(https://www.linkedin.c
(mailto:[email protected])
Community research
(/pages/dzone-community-
research)
Sitemap (/sitemap)
CONTRIBUTE ON DZONE CONTACT US
Article Submission Guidelines 3343 Perimeter Hill Drive
(/articles/dzones-article- Suite 100
submission-guidelines) Nashville, TN 37211
Become a Contributor
[email protected] (/pages/contribute) (mailto:
[email protected])
× Core Program (/pages/core)
Visit the Writers' Zone (/writers-
zone) (/) REFCARDS (/REFCARDZ)
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS) (/users/login.html)
LEGAL
Culture and Methodologies Data Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance
Terms of Service
(/culture-and-methodologies) (/data-engineering) (/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)
(https://technologyadvice.com/terms-
conditions/)
Privacy Policy
(https://technologyadvice.com/privacy-
policy/)