Saturday, December 17, 2022

Log4J addtion to Spring Boot Application

want to add logging capability to our service.

it's very easy thanks to the Springboot, we got logback and SLF4J dependencies automatically, so we could only add a logback.xml in resources folder to the project to customize logging behavior.

To add to this file

Here we defined two appenders

- One writes to console and the other one rights to a file, we can define as many appenders as we want, according to our needs.

 - In the console appender we said, only a pattern for the message.




 - in the file appender, you also specify a file name for logging and again, a pattern of the log Message.

  • Where we define the structure of a log message such as showing the class name, thread ID, time and the log level in the message.
  • And finally, we have a rolling policy here to create a new file and compress and keep the old one after the file reaches a certain size.
  • Finally, we say that we can match the appenders to any package.




For example, here we said two appenders, defined here to all classes that starts with com.microservices.demo package.

That actually means that, our all application classes will be logged by using those two appenders





And here, the root logger will set the log level as a root, which can be overwritten using a specific logger, as we did here.





One more thing about logger is that we can actually define different log levels like trace , Debug, info, warn and error for our logger definition.

And it will work like if you define a lower level it, it will also print the higher levels.

That means Trace level will print all the log messages defined in the code

However, if you set the level as error, all the messages except error will be ignored.

So this way we can control in the configuration how much work will be printed, for example, in production. You don't want to include that much logging, as it can affect the performance of your application because of higher cost.

Having the log feature, I will now update the initialization codes we created in the spring application

class and use the logging framework to log the keywords we defined in the application configuration.






No comments:

Post a Comment