Skip to content

Instantly share code, notes, and snippets.

@bmamatkadyr
Forked from darbyluv2code/MyLoggerConfig.java
Created September 22, 2021 06:02
Show Gist options
  • Save bmamatkadyr/3678297d6a7b70b27920d5863a07fa21 to your computer and use it in GitHub Desktop.
Save bmamatkadyr/3678297d6a7b70b27920d5863a07fa21 to your computer and use it in GitHub Desktop.
Spring Logging for Spring 5.1 - XML Configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--
Add a logger config to see logging messages.
- For more detailed logs, set values to "FINEST"
- For info on logging levels, see: http://www.vogella.com/tutorials/Logging/article.html
-->
<bean id="myLoggerConfig" class="com.luv2code.springdemo.MyLoggerConfig" init-method="initLogger">
<property name="rootLoggerLevel" value="FINE" />
<property name="printedLoggerLevel" value="FINE"/>
</bean>
<!-- Define your beans here -->
<!-- define the dependency -->
<bean id="myFortuneService"
class="com.luv2code.springdemo.HappyFortuneService">
</bean>
<bean id="myCoach"
class="com.luv2code.springdemo.TrackCoach">
<!-- set up constructor injection -->
<constructor-arg ref="myFortuneService" />
</bean>
</beans>
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 org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyLoggerConfig {
private String rootLoggerLevel;
private String printedLoggerLevel;
public void setRootLoggerLevel(String rootLoggerLevel) {
this.rootLoggerLevel = rootLoggerLevel;
}
public void setPrintedLoggerLevel(String printedLoggerLevel) {
this.printedLoggerLevel = printedLoggerLevel;
}
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