MDC Logging using SpringBoot
MDC
Logging using SpringBoot
Introduction
Logging
is an integral part of software development that enables us to better debug the
issue in production. In the development environment we have the freedom of
troubleshooting using breakpoints using any of our favourite IDEs. During the
production, it is not possible that we go with a downtime, add extra logs and
then debug. MDC logging comes to the rescue in this case. Mapped Diagnostic
context comes to the rescue in this case. Its purpose can be extrapolated in
much more ways than this too. Since those are already covered on other blogs
the production support will be covered here.
Pre-requisite
Knowledge of the
following is expected
1.
SpringBoot
2.
Log4j Logging
3.
SL4j logging
Prior to MDC
Extra Info
The logging statements
provide a good way to debug information where one can have different levels of
logging like info, debug etc. Once the logging level is changed, the respective
logger command would get executed. But this is limited to the data that is
added to be logged. If one needs some details of the object which are not being
logged it cannot be obtained. Also, if one adds a lot of debug statements all
of these would spit out redundant data in the log files.
Inputs from multiple users
During the production it
can happen that logs from a particular user is required for any specific
problem. During such times, MDC can help in logging such events.
Another blog already has
the know-how to do that. Adding here for reference.
https://dzone.com/articles/siftingappender-logging
Configuration
In order to configure MDC, add the imports as mentioned below:-
The MDC statements that are desired can be added in the
source code as required. The data from the statements can be enabled based on
the key mentioned in the statements.
For e.g. sample id can be added to the logs, if “sample.id”
is part of the logging configuration in the application.properties.
The corresponding setting is shown in the screen below a
couple of lines.
Output
- Import the given collection mapstruct.postman_collection.json in postman
- Run mvn clean install
- Run mvn springboot:run
- The application will run if port 8080 is available
- Create Sample from the postman collection request
- Get the list of created samples from the postman collection request
Logs in running application look like so:-
Source code
The source code for the example can be found at
https://github.com/shrirange/springboot-mapstruct.git




Comments
Post a Comment