Created
January 30, 2023 21:34
-
-
Save navind062g/b4831dcca8bdb0c67bb942f9200658dc to your computer and use it in GitHub Desktop.
Logging Configuration for Spring Application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.code.section.ten; | |
| import java.util.logging.ConsoleHandler; | |
| import java.util.logging.Level; | |
| import java.util.logging.Logger; | |
| import java.util.logging.SimpleFormatter; | |
| import javax.annotation.PostConstruct; | |
| import org.springframework.beans.factory.annotation.Value; | |
| import org.springframework.context.annotation.AnnotationConfigApplicationContext; | |
| import org.springframework.context.annotation.Configuration; | |
| import org.springframework.context.annotation.PropertySource; | |
| /* mylogger.properties should be in the src path section | |
| Sample values for the file | |
| ======================================================= | |
| root.logger.level=FINEST | |
| printed.logger.level=FINEST | |
| ======================================================= | |
| */ | |
| @Configuration | |
| @PropertySource("classpath:mylogger.properties") | |
| public class MyLoggerConfig { | |
| @Value("${root.logger.level}") | |
| private String rootLoggerLevel; | |
| @Value("${printed.logger.level}") | |
| private String printedLoggerLevel; | |
| @PostConstruct | |
| public void initLogger() { | |
| //parse levels | |
| Level rootLevel = Level.parse(rootLoggerLevel); | |
| Level printedLevel = Level.parse(printedLoggerLevel); | |
| // get logger for the app context | |
| Logger applicationContextLogger = Logger.getLogger(AnnotationConfigApplicationContext.class.getName()); | |
| // get parent logger | |
| Logger loggerParent = applicationContextLogger.getParent(); | |
| // set the root logging level | |
| loggerParent.setLevel(rootLevel); | |
| // set up the console handler | |
| ConsoleHandler consoleHandler = new ConsoleHandler(); | |
| consoleHandler.setLevel(printedLevel); | |
| consoleHandler.setFormatter(new SimpleFormatter()); | |
| //add handler to the logger | |
| loggerParent.addHandler(consoleHandler); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment