Skip to content

Instantly share code, notes, and snippets.

@darbyluv2code
Last active March 12, 2023 10:03
Show Gist options
  • Save darbyluv2code/a49009fe1f92f95a30d2d5f7ac987ce5 to your computer and use it in GitHub Desktop.
Save darbyluv2code/a49009fe1f92f95a30d2d5f7ac987ce5 to your computer and use it in GitHub Desktop.
Spring Logging for Spring 5.1 - All Java Configuration
#
# Set the application logging levels
# - For more detailed logs, set leves to FINEST
# - For info on logging levels, see: http://www.vogella.com/tutorials/Logging/article.html
#
root.logger.level=FINE
printed.logger.level=FINE
package com.luv2code.springdemo;
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;
@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 app context
Logger applicationContextLogger = Logger.getLogger(AnnotationConfigApplicationContext.class.getName());
// get parent logger
Logger loggerParent = applicationContextLogger.getParent();
// set root logging level
loggerParent.setLevel(rootLevel);
// set up console handler
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(printedLevel);
consoleHandler.setFormatter(new SimpleFormatter());
// add handler to the logger
loggerParent.addHandler(consoleHandler);
}
}
@evoyager
Copy link

evoyager commented Oct 5, 2021

How to use it as as Bean in java class based configuration without using @ComponentScan?

@naveenvignesh5 You should mention MyLoggerConfig in context initialization:
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyLoggerConfig.class, SportConfig.class);

@angad-singh97
Copy link

@evoyager
Should this be done even if @componentscan is enabled?

I have added the mylogger.properties file, also added the MyLoggerConfig class with a @configuration annotation. However, the logs do not appear until I explicitly mention the name of the logger as you have mentioned.

Am I missing something here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment