Skip to content

Instantly share code, notes, and snippets.

@TopekoX
Forked from darbyluv2code/MyLoggerConfig.java
Created April 3, 2022 13:18
Show Gist options
  • Save TopekoX/2b20fdb5d3c4dc8bac15260345918e3e to your computer and use it in GitHub Desktop.
Save TopekoX/2b20fdb5d3c4dc8bac15260345918e3e 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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment