Our goal is to figure out how to quickly enable logging for some selected methods or for all methods in the class.
We already considered in one of our posts how to log method with parameters in Java with AspectJ
In this post we’re going to know how to do it easier with the open source library EasyLog (Site, Source code).
EasyLog uses a similar approach and suggests a lot of additional useful features.
Start logging methods
With EasyLog we can start logging by adding the @LogIt
annotation to the method that we want to log
Easy, isn’t it?
If we annotate a class then we activate logging for all the methods that the class contains.
That’s it. Now we log every method call with all parameters passed and the result returned if any.
This is how our log will look like
Awesome!
LogIt annotation parameters
Let’s take a look at the parameters that @LogIt
annotation contains
Level level
level
parameter sets the logging level.
We can set different levels for different methods!
By default it’s INFO
.
Available options: DEBUG
, INFO
, WARN
, ERROR
String label
Labels help you to simplify a search for specific entries in the logs. Just pass another annotation parameter String label
.
By default it’s an empty String
String[] ignoreParameters
The ignoreParameters
parameter allows you to exclude some of parameters from logging
String[] maskFields
You can also mask some fields of the objects that you pass to a method and the object that the method returns.
Note: EasyLog doesn’t modify returned results or passed parameters, just changes how they look in the logs.
Might be used for:
-
masking any sensitive information that shouldn’t be logged
-
decreasing the amount of logged info. For example we can replace huge lists/arrays (in returned results) that are not important in terms of logging with
"XXXMASKEDXXX"
All the field values will be replaced with "XXXMASKEDXXX"
Logging Styles
Available values: PRETTY_PRINT_WITH_NULLS
, PRETTY_PRINT_NO_NULLS
, COMPACT_WITH_NULLS
, MINIMAL
, AS_IS
. By default it’s PRETTY_PRINT_WITH_NULLS
Here PRETTY_PRINT
means “pretty printed JSON”. COMPACT_WITH_NULLS
and MINIMAL
also mean JSON but not “pretty printed”
See the difference
COMPACT_WITH_NULLS
and MINIMAL
These will give you
PRETTY_PRINT_WITH_NULLS
and PRETTY_PRINT_NO_NULLS
will give you
Use PRETTY_PRINT_WITH_NULLS
and COMPACT_WITH_NULLS
if you want to log (serialize) null
’s
Use PRETTY_PRINT_NO_NULLS
and MINIMAL
if you want to exclude nulls from logging.
AS_IS
is used if you want to serialize the parameters and returned result with the toString
method. In this case maskFields
will be ignored
How to setup EasyLog
There are two example projects where you can get familiar with how to make all that beauty real
There is a difference because we setup our pom.xml
differently and use different loggers EasyLogger
and EasyLoggerNoSpring
for Spring and non-Spring projects.
You may also find these posts interesting: