"Welcome To Ashok IT" "Spring Boot and MicroServices" Topic : Spring Boot Logging Date : 08/02/2025 (Session - 120 & 121) _____________________________________________________________________________________________________________________________ Yesterday Session ================= * We have been completed working with Config Server & Config Client in Microservices * As part of our Config Server we have seen how to externalize the configuration into github & gitlab & FileStore. Config Client is used to collect the configurations from Config Server. * Actuators are nothing but production ready features which can be tested through Rest API Endpoints. Git Commands ============ 1) git status >>> gives an information about tracked files(Green color files),untracked files(Red color files) 2) git add . >>> To move all files from untracked state to tracked state in a single go. git add >>> Particular file will movedd from untracked state to tracked state 3) git commit -m >>>> To move the file changes into our local repoistory. 4) git push origin >>>> To move the committed files from local to remote repoistory. 5) git pull >>> It will pull/get the code changes from remote repoistory to local repoistory. 6) git fetch >>> It will fetch all branches and code changes from remote to local repoistory. User-1 >>>> sample branch >>> He made some changes in this branch >>>> Facing some code issue >>> commit on this branch User-2 >>>> git fetch (Getting Remote branches info) >>>> git checkout Ex: git checkout sample 7) git checkout -b >>> creating feature branch on main branch 8) git merge >>> Merging changes from one branch to another branch. Today Session ============= * Logging is one of important aspect of Software development which helps to track activites of an application easily. * During development of project (or) when Debugging code actually we are using SOP statements which can't be useful for realtime development for debugging code. * As we know that SOP statements are always get displayed on Console and not all storing that SOP statements any where in file for future references. Example ======= Develop the Code >>>> Pushed changes to Dev Env >>>> Your Code is working as expected >>>>>> No issues Your code will promoted to other higher environment >>>> QA >>>> In QA your code is not working >>>>> Simply will get the log file of QA environment.... * Inorder to overcome all the problems we need to implement logging mechanism in Project using some logging libraries in Java such as java.util.logging,log4j,Apache Commons Logging,SLF4J,Logback etc., System.out.println("First name :::::" + firstName); // this will print on Application console log.info("First name :::::" + firstName); // this will print in log file of an application * Every logging library main contains three components 1) logger >>>>>> Logger component is used to decide which classes to be logged. Ex:Controller,Service,DAO,Configuration,Helper classes in project etc Entity,POJO,DTO classes are not required for Logging. How to get the logger/log object in the above classes ===================================================== private static Logger logger = LoggerFactory.getLogger(WelcomeController.class); private static Logger logger = LoggerFactory.getLogger(UserService.class); private static Logger logger = LoggerFactory.getLogger(DemoService.class); private static Logger logger = LoggerFactory.getLogger(LoginController.class); Log Methods =========== 1) DEBUG >>>>> logger.debug("This is Debug Message"); >>>> logging for debugging message. 2) INFO >>>>> logger.info("This is info message"); >>>> Logging for Information messsage 3) WARN >>>>> logger.warn("This is Warn Message); >>>> Logging for warnings to user 4) ERROR >>>>> logger.error("This is Error Messsage") >>>> Logging Exceptions 5) FATAL >>>>> logger.fatal("This is Fatal Message"); >>>> Logging for Severity Errors such configuration missings. Setting log level ================= Every Application need to set some log level based on that log level that log messages will be written into log file. 2) Appender >>>>>> Appender Component is used where to store the Log messages 1) FileAppender >>>>>>>>>> It is used to store log messages into File (application.log) 2) ConsoleAppender >>>>>>>>>> It is used to print the log messages to console 3) SMTPAppender >>>>>>>>>> It is used to write log messages to email NOTE ==== Every Application will requires atleast one Appender (or) more than one Appender This appender is at application level. 3) Layout >>>>>> Layout component is used how to print the Log message in required format %d — date, %level — log level , %c — class path, %t — thread executing, %m — message,%n — new line %clr-color,%L-line numnber, %M - Method For More information : https://logging.apache.org/log4j/2.x/manual/layouts.html Spring Boot Logging =================== * Spring boot support logging mechanism by using slf4j & logback libraries. * let us try to understand the log format in spring boot applciation * Let’s break the log message and understand what each term means , 2022–07–16 13:16:51 — Date and Time >>>> %d{yyyy-MM-DD HH:MM:SS} INFO — Log Level >>>> %level 12620 — Process ID >>>> %pid [nio-8080-exec-1] — Thread name >>>> %t com.logging.Controller — Logger name >>>> %c Initializing Spring embedded WebApplicationContext — Log message >>>>> %m * Spring Boot logging will comes along with Starters implictly Spring-boot-starter-web >>>>>>>>>>> Spring-boot-starter >>>>>>>>>>>> spring-boot-starter-logging >>>>>>>>>>>>>>>spring-jcl(Spring Commons Logging Bridge) * By Default Logging level of an Spring Boot Application is "INFO" Means Info,Error,Warn Messages are get logged automatically. * We can change the log level in spring boot application by adding the below configuration entry in application.properties application.properties ====================== #Server Port configuration server.port=9878 #changing the log level of spring boot application #logging.level.root=debug #logging.level.com.ashokit=info #logging.level.org.springframework.web=error #log message layout configuration logging.pattern.console=%d{dd-MM-YYYY HH:MM:SS} %clr([%level]){blue} [%c]-{%M} {%t} %m%n #Writing the logs into file logging.file.name=logs/application.log #log message layout configuration logging.pattern.file=%d{dd-MM-YYYY HH:MM:SS} %clr([%level]){blue} [%c]-{%M} {%t} %m%n #Logging banner into application.log spring.main.banner-mode=log #setting some size to log files logging.logback.rollingpolicy.max-file-size=20KB #15days log files will be stored logging.logback.rollingpolicy.max-history=15 WelcomeController.java ====================== package com.ashokit.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/welcome") //@Slf4j public class WelcomeController { private static Logger log = LoggerFactory.getLogger(WelcomeController.class); @GetMapping("/{username}") public ResponseEntity getWelcome(@PathVariable("username") String username){ log.debug("This is for Debug Message"); log.info("This is for Information Message"); log.error("This is for Error Message"); log.trace("This is for Trace Message"); log.warn("This is for Warn Message"); return new ResponseEntity("Welcome To AshokIT"+username,HttpStatus.OK); } } Testing the Application ======================= * Run the Spring Boot Application and access the API Endpoint to generat the log messages on console http://localhost:9878/welcome/Mahesh * Refresh our project and find logs folder in that log file is available NOTE ==== * Basically in application development we are not at all configuring logging properties in application.properties (or) application.yml file because if we require any changes we need to modify the properties (or) yaml file changing these things will take redeployement and restarting the application. * Inorder to overcome the above problem we need to maintain logging configuration in xml file to avoid redeployement simply requires restarting of an application. * In spring boot application we can maintain logging configuration with xml file name as logback.xml (or) logback-spring.xml. * Create xml file under src/main/resources logback.xml =========== ${LOG_FILE} logs/archived/applicationlogs.%d{yyyy-MM-dd}.%i.log 5KB 20KB 60 %d %p %c{1.} [%t] %m%n %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n smtp.gmail.com 587 true mahesh.ashokit@gmail.com APP Password mahesh.ashokit@gmail.com mahesh.ashokit@gmail.com ApplicatioErrors: %logger{20} - %m