spring boot 2 + log4j2 over slf4j not writing logs to file - spring-boot

In my application, I'm using spring boot 2.0.3 and have slf4j with log4j2 configured for logging.
However, I'm not able to get the setup write the logs to the file. I tried many ways but could not make it work. I don't understand what I'm missing here :/
My pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.boot.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>${spring.boot.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>${spring.boot.version}</version>
</dependency>
My log4j2.properties file
status = debug
name= properties_configuration
# Give directory path where log files should get stored
property.basePath = /A/B/c-web
# ConsoleAppender will print logs on console
appender.console.type = Console
appender.console.name = consoleLogger
appender.console.target = SYSTEM_OUT
appender.console.layout.type = PatternLayout
# Specify the pattern of the logs
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n
# RollingFileAppender will print logs in file which can be rotated based on time or size
appender.rolling.type = RollingFile
appender.rolling.name = fileLogger
appender.rolling.fileName= ${basePath}/c-web.log
appender.rolling.filePattern= ${basePath}/archive/c-web_%d{yyyyMMdd}.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n
appender.rolling.policies.type = Policies
# Rotate log file each day and keep 30 days worth
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.delete.type = Delete
appender.rolling.strategy.delete.basePath = ${basePath}/archive
appender.rolling.strategy.delete.maxDepth = 1
appender.rolling.strategy.delete.ifLastModified.type = IfLastModified
# Delete files older than 30 days
appender.rolling.strategy.delete.ifLastModified.age = 30d
# Mention package name here in place of example. Classes in this package or subpackages will use ConsoleAppender and RollingFileAppender for logging
logger.rolling.name = com.x
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = fileLogger
logger.rolling.appenderRef.console.ref = consoleLogger
# Configure root logger for logging error logs in classes which are in package other than above specified package
rootLogger.level = info
rootLogger.additivity = false
rootLogger.appenderRef.rolling.ref = fileLogger
rootLogger.appenderRef.console.ref = consoleLogger
Application log during bootup
2018-10-28 20:14:50,463 main DEBUG PluginManager 'Core' found 116 plugins
2018-10-28 20:14:50,463 main DEBUG PluginManager 'Level' found 0 plugins
2018-10-28 20:14:50,468 main DEBUG Building Plugin[name=property, class=org.apache.logging.log4j.core.config.Property].
2018-10-28 20:14:50,483 main DEBUG PluginManager 'TypeConverter' found 26 plugins
2018-10-28 20:14:50,493 main DEBUG createProperty(name="basePath", value="/A/B/c-web")
2018-10-28 20:14:50,493 main DEBUG Building Plugin[name=properties, class=org.apache.logging.log4j.core.config.PropertiesPlugin].
2018-10-28 20:14:50,498 main DEBUG configureSubstitutor(={basePath=/A/B/c-web}, Configuration(properties_configuration))
2018-10-28 20:14:50,499 main DEBUG PluginManager 'Lookup' found 13 plugins
2018-10-28 20:14:50,499 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2018-10-28 20:14:50,499 main DEBUG createAppenderRef(ref="consoleLogger", level="null", Filter=null)
2018-10-28 20:14:50,500 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2018-10-28 20:14:50,500 main DEBUG createAppenderRef(ref="fileLogger", level="null", Filter=null)
2018-10-28 20:14:50,500 main DEBUG Building Plugin[name=logger, class=org.apache.logging.log4j.core.config.LoggerConfig].
2018-10-28 20:14:50,504 main DEBUG createLogger(additivity="false", level="DEBUG", name="com.x", includeLocation="null", ={consoleLogger, fileLogger}, ={}, Configuration(properties_configuration), Filter=null)
2018-10-28 20:14:50,506 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2018-10-28 20:14:50,507 main DEBUG createAppenderRef(ref="consoleLogger", level="null", Filter=null)
2018-10-28 20:14:50,507 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2018-10-28 20:14:50,507 main DEBUG createAppenderRef(ref="fileLogger", level="null", Filter=null)
2018-10-28 20:14:50,508 main DEBUG Building Plugin[name=root, class=org.apache.logging.log4j.core.config.LoggerConfig$RootLogger].
2018-10-28 20:14:50,509 main DEBUG createLogger(additivity="null", level="INFO", includeLocation="null", ={consoleLogger, fileLogger}, ={}, Configuration(properties_configuration), Filter=null)
2018-10-28 20:14:50,509 main DEBUG Building Plugin[name=loggers, class=org.apache.logging.log4j.core.config.LoggersPlugin].
2018-10-28 20:14:50,510 main DEBUG createLoggers(={com.x, root})
2018-10-28 20:14:50,510 main DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2018-10-28 20:14:50,515 main DEBUG PatternLayout$Builder(pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n", PatternSelector=null, Configuration(properties_configuration), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2018-10-28 20:14:50,515 main DEBUG PluginManager 'Converter' found 47 plugins
2018-10-28 20:14:50,528 main DEBUG Building Plugin[name=IfLastModified, class=org.apache.logging.log4j.core.appender.rolling.action.IfLastModified].
2018-10-28 20:14:50,529 main DEBUG createAgeCondition(age="P30D", ={})
2018-10-28 20:14:50,530 main DEBUG org.apache.logging.log4j.core.util.SystemClock does not support precise timestamps.
2018-10-28 20:14:50,531 main DEBUG Building Plugin[name=Delete, class=org.apache.logging.log4j.core.appender.rolling.action.DeleteAction].
2018-10-28 20:14:50,532 main DEBUG createDeleteAction(basePath="/A/B/c-web/archive", followLinks="false", maxDepth="1", testMode="false", PathSorter=null, ={IfLastModified(age=P30D)}, ScriptCondition=null, Configuration(properties_configuration))
2018-10-28 20:14:50,532 main DEBUG Building Plugin[name=DefaultRolloverStrategy, class=org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy].
2018-10-28 20:14:50,542 main DEBUG DefaultRolloverStrategy$Builder(max="null", min="null", fileIndex="null", compressionLevel="null", ={DeleteAction[basePath=/A/B/c-web/archive, options=[], maxDepth=1, conditions=[IfLastModified(age=P30D)]]}, stopCustomActionsOnError="null", tempCompressedFilePattern="null", Configuration(properties_configuration))
2018-10-28 20:14:50,542 main DEBUG Building Plugin[name=TimeBasedTriggeringPolicy, class=org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy].
2018-10-28 20:14:50,544 main DEBUG TimeBasedTriggeringPolicy$Builder(interval="1", modulate="true", maxRandomDelay="null")
2018-10-28 20:14:50,544 main DEBUG Building Plugin[name=Policies, class=org.apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy].
2018-10-28 20:14:50,545 main DEBUG createPolicy(={TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=true)})
2018-10-28 20:14:50,545 main DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.RollingFileAppender].
2018-10-28 20:14:50,549 main DEBUG RollingFileAppender$Builder(fileName="/A/B/c-web/c-web.log", filePattern="/A/B/c-web/archive/c-web_%d{yyyyMMdd}.log.gz", append="null", locking="null", Policies(CompositeTriggeringPolicy(policies=[TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=true)])), DefaultRolloverStrategy(DefaultRolloverStrategy(min=1, max=7, useMax=true)), advertise="null", advertiseUri="null", createOnDemand="null", filePermissions="null", fileOwner="null", fileGroup="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n), name="fileLogger", Configuration(properties_configuration), Filter=null)
2018-10-28 20:14:50,554 main DEBUG Starting RollingFileManager /A/B/c-web/c-web.log
2018-10-28 20:14:50,556 main DEBUG PluginManager 'FileConverter' found 2 plugins
2018-10-28 20:14:50,557 main DEBUG Setting prev file time to 2018-10-28T19:16:05.000+0530
2018-10-28 20:14:50,559 main DEBUG Initializing triggering policy CompositeTriggeringPolicy(policies=[TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=true)])
2018-10-28 20:14:50,560 main DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2018-10-28 20:14:50,561 main DEBUG PatternLayout$Builder(pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n", PatternSelector=null, Configuration(properties_configuration), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2018-10-28 20:14:50,561 main DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.ConsoleAppender].
2018-10-28 20:14:50,563 main DEBUG ConsoleAppender$Builder(target="SYSTEM_OUT", follow="null", direct="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n), name="consoleLogger", Configuration(properties_configuration), Filter=null)
2018-10-28 20:14:50,564 main DEBUG Starting OutputStreamManager SYSTEM_OUT.false.false
2018-10-28 20:14:50,565 main DEBUG Building Plugin[name=appenders, class=org.apache.logging.log4j.core.config.AppendersPlugin].
2018-10-28 20:14:50,565 main DEBUG createAppenders(={fileLogger, consoleLogger})
2018-10-28 20:14:50,566 main DEBUG Configuration org.apache.logging.log4j.core.config.properties.PropertiesConfiguration#23cd925 initialized
2018-10-28 20:14:50,566 main DEBUG Starting configuration org.apache.logging.log4j.core.config.properties.PropertiesConfiguration#23cd925
2018-10-28 20:14:50,567 main DEBUG Started configuration org.apache.logging.log4j.core.config.properties.PropertiesConfiguration#23cd925 OK.
2018-10-28 20:14:50,567 main DEBUG Shutting down OutputStreamManager SYSTEM_OUT.false.false-1
2018-10-28 20:14:50,568 main DEBUG Shut down OutputStreamManager SYSTEM_OUT.false.false-1, all resources released: true
2018-10-28 20:14:50,568 main DEBUG Appender DefaultConsole-1 stopped with status true
2018-10-28 20:14:50,568 main DEBUG Stopped org.apache.logging.log4j.core.config.DefaultConfiguration#699259d8 OK
2018-10-28 20:14:50,611 main DEBUG Registering MBean org.apache.logging.log4j2:type=6be184cd
2018-10-28 20:14:50,613 main DEBUG Registering MBean org.apache.logging.log4j2:type=6be184cd,component=StatusLogger
2018-10-28 20:14:50,615 main DEBUG Registering MBean org.apache.logging.log4j2:type=6be184cd,component=ContextSelector
2018-10-28 20:14:50,618 main DEBUG Registering MBean org.apache.logging.log4j2:type=6be184cd,component=Loggers,name=
2018-10-28 20:14:50,619 main DEBUG Registering MBean org.apache.logging.log4j2:type=6be184cd,component=Loggers,name=com.x
2018-10-28 20:14:50,620 main DEBUG Registering MBean org.apache.logging.log4j2:type=6be184cd,component=Appenders,name=fileLogger
2018-10-28 20:14:50,621 main DEBUG Registering MBean org.apache.logging.log4j2:type=6be184cd,component=Appenders,name=consoleLogger
2018-10-28 20:14:50,623 main DEBUG org.apache.logging.log4j.core.util.SystemClock does not support precise timestamps.
2018-10-28 20:14:50,623 main DEBUG Reconfiguration complete for context[name=6be184cd] at URI <project-path>/target/classes/log4j2.properties (org.apache.logging.log4j.core.LoggerContext#ac76de5) with optional ClassLoader: null
2018-10-28 20:14:50,623 main DEBUG Shutdown hook enabled. Registering a new one.
2018-10-28 20:14:50,624 main DEBUG LoggerContext[name=6be184cd, org.apache.logging.log4j.core.LoggerContext#ac76de5] started OK.
2018-10-28 20:14:50,971 main DEBUG Using configurationFactory org.apache.logging.log4j.core.config.ConfigurationFactory$Factory#7ae5dec6
2018-10-28 20:14:50,974 main INFO Log4j appears to be running in a Servlet environment, but there's no log4j-web module available. If you want better web container support, please add the log4j-web JAR to your web archive or server lib directory.
Please let me know if you need any other information.
appreciate your help. Thanks in advance.

It turned out to be pretty simple.Spring boot was not loading the log4j2 configuration file properly during the Application starup.I just had to explicitly mention it.
I was able to get it working by adding
logging.config=src/main/resources/log4j2.properties
to my application.properties file.

Related

spring diasable logging for controller

There is a polling service which fills up my log
2022-01-09T05:24:32,827 DEBUG [ajp-nio-8009-exec-7] o.s.c.l.LogFormatUtils: GET "/VenusD/anonymous/
Somewhat like above. I just need to disable spring logging for a selected controller or request mapping.
What is the right way of doing it? How can I probably exclude it?
If you don't have to change log level of package, comment please.
You can set log level of pacakge.
My log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout
pattern="[%d{yyyy-MM-dd HH:mm:ss}:%-3relative][%thread] %-5level %logger{100}.%M - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="DEBUG" additivity="false">
<AppenderRef ref="console" />
</Root>
<!-- <Logger name="org.springframework.web.servlet.DispatcherServlet" level="warn"></Logger> -->
</Loggers>
</Configuration>
My log, When I set log levl debug
[2022-01-09 10:01:34:5876][http-nio-8080-exec-1] INFO org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].log - Initializing Spring DispatcherServlet 'dispatcherServlet'
[2022-01-09 10:01:34:5877][http-nio-8080-exec-1] INFO org.springframework.web.servlet.DispatcherServlet.initServletBean - Initializing Servlet 'dispatcherServlet'
[2022-01-09 10:01:34:5877][http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet.initMultipartResolver - Detected StandardServletMultipartResolver
[2022-01-09 10:01:34:5877][http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet.initLocaleResolver - Detected AcceptHeaderLocaleResolver
[2022-01-09 10:01:34:5877][http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet.initThemeResolver - Detected FixedThemeResolver
[2022-01-09 10:01:34:5877][http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet.initRequestToViewNameTranslator - Detected org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator#5889aa66
[2022-01-09 10:01:34:5878][http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet.initFlashMapManager - Detected org.springframework.web.servlet.support.SessionFlashMapManager#25bd45e9
[2022-01-09 10:01:34:5878][http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet.initServletBean - enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
[2022-01-09 10:01:34:5878][http-nio-8080-exec-1] INFO org.springframework.web.servlet.DispatcherServlet.initServletBean - Completed initialization in 1 ms
[2022-01-09 10:01:34:5890][http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet.traceDebug - GET "/", parameters={}
[2022-01-09 10:01:34:5894][http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getHandler - Mapped to com.example.rest.timeout.controller.ControllerTest#get()
[2022-01-09 10:01:34:5919][http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.writeWithMessageConverters - Using 'application/json;q=0.8', given [text/html, application/xhtml+xml, image/avif, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8] and supported [application/json, application/*+json, application/json, application/*+json]
[2022-01-09 10:01:34:5919][http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.writeWithMessageConverters - Nothing to write: null body
[2022-01-09 10:01:34:5921][http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet.logResult - Completed 200 OK
My log, When I remove following comment in log4j2.xml
<!-- <Logger name="org.springframework.web.servlet.DispatcherServlet" level="warn"></Logger> -->
to
<Logger name="org.springframework.web.servlet.DispatcherServlet" level="warn"></Logger>
Debug log level of org.springframework.web.servlet.DispatcherServlet is removed.
[2022-01-09 10:12:34:666106][http-nio-8080-exec-1] INFO org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].log - Initializing Spring DispatcherServlet 'dispatcherServlet'
[2022-01-09 10:12:34:666108][http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getHandler - Mapped to com.example.rest.timeout.controller.ControllerTest#get()
[2022-01-09 10:12:34:666109][http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.writeWithMessageConverters - Using 'application/json;q=0.8', given [text/html, application/xhtml+xml, image/avif, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8] and supported [application/json, application/*+json, application/json, application/*+json]
[2022-01-09 10:12:34:666110][http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.writeWithMessageConverters - Nothing to write: null body

Spring Session JDBC Problem adding in my project

currently I have a project with Spring MVC which already interact with Database(MariaDB) and I would like to try the spring-session-jdbc. I found the documentation in this spring-session , I do what the documentation is says but the app don't start when I deploy it in the Tomcat. And the log in the Tomcat is not very helpful. Here is my code:
#Configuration
#PropertySource("classpath:application.properties")
#EnableTransactionManagement
#EnableJdbcHttpSession
#ComponentScans(value = {#ComponentScan("com.havistudio.web.testapp.dao"), #ComponentScan("com.havistudio.web.testapp.service")})
public class AppConfig {
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.havistudio.web.testapp.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setJdbcUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
dataSource.setConnectionTimeout(Long.parseLong(environment.getRequiredProperty("spring.datasource.hikari.connection-timeout")));
dataSource.setMinimumIdle(Integer.parseInt(environment.getRequiredProperty("spring.datasource.hikari.minimum-idle")));
dataSource.setMaximumPoolSize(Integer.parseInt(environment.getRequiredProperty("spring.datasource.hikari.maximum-pool-size")));
dataSource.setIdleTimeout(Long.parseLong(environment.getRequiredProperty("spring.datasource.hikari.idle-timeout")));
dataSource.setMaxLifetime(Long.parseLong(environment.getRequiredProperty("spring.datasource.hikari.max-lifetime")));
dataSource.setAutoCommit(Boolean.parseBoolean(environment.getRequiredProperty("spring.datasource.hikari.auto-commit")));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
#Bean
public JavaMailSender getMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
//Using gmail
mailSender.setHost("mail.test.com");
mailSender.setPort(587);
mailSender.setUsername("info#test.com");
mailSender.setPassword("dsffsdfsdfsd");
Properties javaMailProperties = new Properties();
javaMailProperties.put("mail.smtp.auth", "true");
javaMailProperties.put("mail.smtp.starttls.enable", "true");
javaMailProperties.put("mail.smtp.ssl.trust", "mail.test.com");
//javaMailProperties.put("mail.debug", "true");//Prints out everything on screen
mailSender.setJavaMailProperties(javaMailProperties);
return mailSender;
}
}
My initializer:
public class MyInitializer extends AbstractHttpSessionApplicationInitializer {
public MyInitializer() {
super(AppConfig.class);
}
}
My application.properties
spring.session.store-type=jdbc
pom.xml
<!-- Spring Session JDBC -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</artifactId>
<version>2.5.1</version>
</dependency>
My log:
21-Aug-2021 18:23:45.336 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.startup.HostConfig.undeploy Undeploying context [/TzokerStatisticsApp]
21-Aug-2021 18:23:45.694 INFO [localhost-startStop-3] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp.war]
2021-08-21 18:23:50,242 localhost-startStop-3 DEBUG Apache Log4j Core 2.14.1 initializing configuration XmlConfiguration[location=C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml]
2021-08-21 18:23:50,246 localhost-startStop-3 DEBUG Installed 1 script engine
Warning: Nashorn engine is planned to be removed from a future JDK release
2021-08-21 18:23:50,252 localhost-startStop-3 DEBUG Oracle Nashorn version: 11.0.11, language: ECMAScript, threading: Not Thread Safe, compile: true, names: [nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript], factory class: jdk.nashorn.api.scripting.NashornScriptEngineFactory
2021-08-21 18:23:50,253 localhost-startStop-3 DEBUG PluginManager 'Core' found 122 plugins
2021-08-21 18:23:50,253 localhost-startStop-3 DEBUG PluginManager 'Level' found 0 plugins
2021-08-21 18:23:50,257 localhost-startStop-3 DEBUG PluginManager 'Lookup' found 16 plugins
2021-08-21 18:23:50,260 localhost-startStop-3 DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2021-08-21 18:23:50,273 localhost-startStop-3 DEBUG PluginManager 'TypeConverter' found 26 plugins
2021-08-21 18:23:50,282 localhost-startStop-3 DEBUG PatternLayout$Builder(pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n", PatternSelector=null, Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2021-08-21 18:23:50,283 localhost-startStop-3 DEBUG PluginManager 'Converter' found 44 plugins
2021-08-21 18:23:50,284 localhost-startStop-3 DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.ConsoleAppender].
2021-08-21 18:23:50,294 localhost-startStop-3 DEBUG ConsoleAppender$Builder(target="SYSTEM_OUT", follow="null", direct="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n), name="LogToConsole", Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Filter=null, ={})
2021-08-21 18:23:50,296 localhost-startStop-3 DEBUG Starting OutputStreamManager SYSTEM_OUT.false.false
2021-08-21 18:23:50,296 localhost-startStop-3 DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2021-08-21 18:23:50,297 localhost-startStop-3 DEBUG PatternLayout$Builder(pattern="%d %p %c{1.} [%t] %m%n", PatternSelector=null, Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2021-08-21 18:23:50,323 localhost-startStop-3 DEBUG Building Plugin[name=TimeBasedTriggeringPolicy, class=org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy].
2021-08-21 18:23:50,327 localhost-startStop-3 DEBUG TimeBasedTriggeringPolicy$Builder(interval="null", modulate="null", maxRandomDelay="null")
2021-08-21 18:23:50,327 localhost-startStop-3 DEBUG Building Plugin[name=SizeBasedTriggeringPolicy, class=org.apache.logging.log4j.core.appender.rolling.SizeBasedTriggeringPolicy].
2021-08-21 18:23:50,333 localhost-startStop-3 DEBUG createPolicy(size="1 MB")
2021-08-21 18:23:50,335 localhost-startStop-3 DEBUG Building Plugin[name=Policies, class=org.apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy].
2021-08-21 18:23:50,336 localhost-startStop-3 DEBUG createPolicy(={TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false), SizeBasedTriggeringPolicy(size=1048576)})
2021-08-21 18:23:50,336 localhost-startStop-3 DEBUG Building Plugin[name=DefaultRolloverStrategy, class=org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy].
2021-08-21 18:23:50,339 localhost-startStop-3 DEBUG DefaultRolloverStrategy$Builder(max="10", min="null", fileIndex="null", compressionLevel="null", ={}, stopCustomActionsOnError="null", tempCompressedFilePattern="null", Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml))
2021-08-21 18:23:50,341 localhost-startStop-3 DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.RollingRandomAccessFileAppender].
2021-08-21 18:23:50,344 localhost-startStop-3 DEBUG RollingRandomAccessFileAppender$Builder(fileName="logs/TzokerStatisticsApp/app.log", filePattern="logs/TzokerStatisticsApp/${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz", append="null", Policies(CompositeTriggeringPolicy(policies=[TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false), SizeBasedTriggeringPolicy(size=1048576)])), DefaultRolloverStrategy(DefaultRolloverStrategy(min=1, max=10, useMax=true)), advertise="null", advertiseURI="null", filePermissions="null", fileOwner="null", fileGroup="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d %p %c{1.} [%t] %m%n), name="LogToRollingRandomAccessFile", Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Filter=null, ={})
2021-08-21 18:23:50,354 localhost-startStop-3 DEBUG Starting RollingRandomAccessFileManager logs/TzokerStatisticsApp/app.log
2021-08-21 18:23:50,357 localhost-startStop-3 DEBUG PluginManager 'FileConverter' found 2 plugins
2021-08-21 18:23:50,365 localhost-startStop-3 DEBUG Setting prev file time to 2021-08-16T19:38:00.766+0300
2021-08-21 18:23:50,365 localhost-startStop-3 DEBUG Initializing triggering policy CompositeTriggeringPolicy(policies=[TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false), SizeBasedTriggeringPolicy(size=1048576)])
2021-08-21 18:23:50,366 localhost-startStop-3 DEBUG Initializing triggering policy TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false)
2021-08-21 18:23:50,367 localhost-startStop-3 DEBUG Initializing triggering policy SizeBasedTriggeringPolicy(size=1048576)
2021-08-21 18:23:50,367 localhost-startStop-3 DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2021-08-21 18:23:50,368 localhost-startStop-3 DEBUG createAppenderRef(ref="LogToRollingRandomAccessFile", level="null", Filter=null)
2021-08-21 18:23:50,368 localhost-startStop-3 DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.AsyncAppender].
2021-08-21 18:23:50,370 localhost-startStop-3 DEBUG AsyncAppender$Builder(={LogToRollingRandomAccessFile}, errorRef="null", blocking="null", shutdownTimeout="null", bufferSize="null", name="Async", includeLocation="null", Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), ignoreExceptions="null", BlockingQueueFactory=null, Filter=null, ={})
2021-08-21 18:23:50,371 localhost-startStop-3 DEBUG Building Plugin[name=appenders, class=org.apache.logging.log4j.core.config.AppendersPlugin].
2021-08-21 18:23:50,372 localhost-startStop-3 DEBUG createAppenders(={LogToConsole, LogToRollingRandomAccessFile, Async})
2021-08-21 18:23:50,373 localhost-startStop-3 DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2021-08-21 18:23:50,373 localhost-startStop-3 DEBUG createAppenderRef(ref="Async", level="null", Filter=null)
2021-08-21 18:23:50,373 localhost-startStop-3 DEBUG Building Plugin[name=logger, class=org.apache.logging.log4j.core.config.LoggerConfig].
2021-08-21 18:23:50,376 localhost-startStop-3 DEBUG createLogger(additivity="false", level="DEBUG", name="com.havistudio.web.testapp", includeLocation="null", ={Async}, ={}, Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Filter=null)
2021-08-21 18:23:50,382 localhost-startStop-3 DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2021-08-21 18:23:50,382 localhost-startStop-3 DEBUG createAppenderRef(ref="LogToConsole", level="null", Filter=null)
2021-08-21 18:23:50,383 localhost-startStop-3 DEBUG Building Plugin[name=root, class=org.apache.logging.log4j.core.config.LoggerConfig$RootLogger].
2021-08-21 18:23:50,384 localhost-startStop-3 DEBUG createLogger(additivity="null", level="ERROR", includeLocation="null", ={LogToConsole}, ={}, Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Filter=null)
2021-08-21 18:23:50,385 localhost-startStop-3 DEBUG Building Plugin[name=loggers, class=org.apache.logging.log4j.core.config.LoggersPlugin].
2021-08-21 18:23:50,386 localhost-startStop-3 DEBUG createLoggers(={com.havistudio.web.testapp.root})
2021-08-21 18:23:50,388 localhost-startStop-3 DEBUG Configuration XmlConfiguration[location=C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml] initialized
2021-08-21 18:23:50,388 localhost-startStop-3 DEBUG Starting configuration XmlConfiguration[location=C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml]
2021-08-21 18:23:50,395 localhost-startStop-3 DEBUG org.apache.logging.log4j.core.util.SystemClock supports precise timestamps.
2021-08-21 18:23:50,399 localhost-startStop-3 DEBUG Started configuration XmlConfiguration[location=C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml] OK.
2021-08-21 18:23:50,399 localhost-startStop-3 DEBUG Shutting down OutputStreamManager SYSTEM_OUT.false.false-1
2021-08-21 18:23:50,400 localhost-startStop-3 DEBUG OutputStream closed
2021-08-21 18:23:50,400 localhost-startStop-3 DEBUG Shut down OutputStreamManager SYSTEM_OUT.false.false-1, all resources released: true
2021-08-21 18:23:50,400 localhost-startStop-3 DEBUG Appender DefaultConsole-1 stopped with status true
2021-08-21 18:23:50,401 localhost-startStop-3 DEBUG Stopped org.apache.logging.log4j.core.config.DefaultConfiguration#39d9ebd0 OK
2021-08-21 18:23:50,407 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b
2021-08-21 18:23:50,410 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=StatusLogger
2021-08-21 18:23:50,412 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=ContextSelector
2021-08-21 18:23:50,415 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=Loggers,name=
2021-08-21 18:23:50,415 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=Loggers,name=com.havistudio.web.testapp
2021-08-21 18:23:50,417 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=Appenders,name=LogToRollingRandomAccessFile
2021-08-21 18:23:50,418 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=Appenders,name=LogToConsole
2021-08-21 18:23:50,420 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=AsyncAppenders,name=Async
2021-08-21 18:23:50,421 localhost-startStop-3 DEBUG Reconfiguration complete for context[name=5a383f6b] at URI C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml (org.apache.logging.log4j.core.LoggerContext#73aa23c5) with optional ClassLoader: null
2021-08-21 18:23:50,423 localhost-startStop-3 DEBUG Shutdown hook enabled. Registering a new one.
2021-08-21 18:23:50,425 localhost-startStop-3 DEBUG LoggerContext[name=5a383f6b, org.apache.logging.log4j.core.LoggerContext#73aa23c5] started OK.
21-Aug-2021 18:23:50.606 INFO [localhost-startStop-3] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
[localhost-startStop-3] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-2 - Starting...
[localhost-startStop-3] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-2 - Start completed.
21-Aug-2021 18:23:51.592 SEVERE [localhost-startStop-3] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
21-Aug-2021 18:23:51.593 SEVERE [localhost-startStop-3] org.apache.catalina.core.StandardContext.startInternal Context [/TzokerStatisticsApp] startup failed due to previous errors
[localhost-startStop-3] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-2 - Shutdown initiated...
[localhost-startStop-3] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-2 - Shutdown completed.
21-Aug-2021 18:23:51.624 WARNING [localhost-startStop-3] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [TzokerStatisticsApp] registered the JDBC driver [org.mariadb.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
21-Aug-2021 18:23:51.624 WARNING [localhost-startStop-3] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [TzokerStatisticsApp] appears to have started a thread named [Log4j2-AsyncAppenderEventDispatcher-1-Async] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
java.base#11.0.11/jdk.internal.misc.Unsafe.park(Native Method)
java.base#11.0.11/java.util.concurrent.locks.LockSupport.park(LockSupport.java:194)
java.base#11.0.11/java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2081)
java.base#11.0.11/java.util.concurrent.ArrayBlockingQueue.take(ArrayBlockingQueue.java:417)
org.apache.logging.log4j.core.appender.AsyncAppenderEventDispatcher.dispatchAll(AsyncAppenderEventDispatcher.java:70)
org.apache.logging.log4j.core.appender.AsyncAppenderEventDispatcher.run(AsyncAppenderEventDispatcher.java:62)
21-Aug-2021 18:23:51.627 INFO [localhost-startStop-3] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp.war] has finished in [5,933] ms
I am sure I am missing something here, but I don't know what is it.
Finally, I found what was wrong! I took a deeper look in the logs file and specifically in the localhost*.log file and I found this:
3 Spring WebApplicationInitializers detected on classpath
22-Aug-2021 11:15:52.337 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
22-Aug-2021 11:15:53.251 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:263)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4768)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5236)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:754)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:744)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:980)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1851)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829)
Then I modify my MyInitializer class to this:
public class MyInitializer extends AbstractHttpSessionApplicationInitializer {
}
And immediately it worked like a charm!

Log4J2 not working on Spring Boot on many levels

I am trying to use log4j2 in a Spring Boot application, but it is going wrong on several levels.
This is a very simple Hello World application, just trying to get things working before I try it in production code. It is just a simple Initializr-generated Spring Boot application, with no added dependencies.
Problem #1 is that I am getting the following warnings, so I tried adding exclusions, but so far nothing is working
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/vgray/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/vgray/.m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.13.3/log4j-slf4j-impl-2.13.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
Here is the pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sample</groupId>
<artifactId>log4j2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>log4j2</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<log4j2.version>2.13.3</log4j2.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Problem #2 (I assume related) is that I have log4j2.xml in my src/main/resources dir, but it seems to be ignored.
Here is the log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
<Properties>
<Property name="basePath">E:\dev\log4j2\\logs</Property>
</Properties>
<Appenders>
<RollingFile name="fileLogger" fileName="${basePath}/app-info.log" filePattern="${basePath}/app-info-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
</RollingFile>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="[%-5level] %d{MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="Log4j2Application" level="debug" additivity="true">
<appender-ref ref="fileLogger" level="debug" />
</Logger>
<Root level="debug" additivity="false">
<appender-ref ref="console" />
</Root>
</Loggers>
</Configuration>
I am assuming it is ignored, because the pattern is supposed to be MM-dd..., but the log messages are logging differently.
Here is my entire Spring Boot program:
package com.vgray.sample.log4j2;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Log4j2Application {
private static final Logger logger = LogManager.getLogger("Log4j2Application");
public static void main(String[] args) {
logger.trace("A TRACE Message");
logger.debug("A DEBUG Message");
logger.info("An INFO Message");
logger.warn("A WARN Message");
logger.error("An ERROR Message");
logger.error("Error Message Logged !!!", new NullPointerException("NullError"));
SpringApplication.run(Log4j2Application.class, args);
}
}
Here is my entire log
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/vgray/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/vgray/.m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.13.3/log4j-slf4j-impl-2.13.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
21:20:18.355 [main] DEBUG Log4j2Application - A DEBUG Message
21:20:18.358 [main] INFO Log4j2Application - An INFO Message
21:20:18.358 [main] WARN Log4j2Application - A WARN Message
21:20:18.358 [main] ERROR Log4j2Application - An ERROR Message
21:20:18.361 [main] ERROR Log4j2Application - Error Message Logged !!!
java.lang.NullPointerException: NullError
at com.vgray.sample.log4j2.Log4j2Application.main(Log4j2Application.java:19)
21:20:18.531 [restartedMain] DEBUG Log4j2Application - A DEBUG Message
21:20:18.532 [restartedMain] INFO Log4j2Application - An INFO Message
21:20:18.532 [restartedMain] WARN Log4j2Application - A WARN Message
21:20:18.532 [restartedMain] ERROR Log4j2Application - An ERROR Message
21:20:18.532 [restartedMain] ERROR Log4j2Application - Error Message Logged !!!
java.lang.NullPointerException: NullError
at com.vgray.sample.log4j2.Log4j2Application.main(Log4j2Application.java:19)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.2)
2021-02-28 21:20:19.087 INFO 69604 --- [ restartedMain] c.v.sample.log4j2.Log4j2Application : Starting Log4j2Application using Java 11.0.3 on DESKTOP-AM6DIPA with PID 69604 (E:\dev\log4j2\target\classes started by vgray in e:\dev\log4j2)
2021-02-28 21:20:19.089 INFO 69604 --- [ restartedMain] c.v.sample.log4j2.Log4j2Application : No active profile set, falling back to default profiles: default
2021-02-28 21:20:19.174 INFO 69604 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-02-28 21:20:19.174 INFO 69604 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-02-28 21:20:20.352 INFO 69604 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-02-28 21:20:20.364 INFO 69604 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-02-28 21:20:20.364 INFO 69604 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.41]
2021-02-28 21:20:20.451 INFO 69604 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-02-28 21:20:20.451 INFO 69604 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1275 ms
2021-02-28 21:20:20.657 INFO 69604 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-02-28 21:20:20.829 INFO 69604 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2021-02-28 21:20:20.862 INFO 69604 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-02-28 21:20:20.876 INFO 69604 --- [ restartedMain] c.v.sample.log4j2.Log4j2Application : Started Log4j2Application in 2.33 seconds (JVM running for 3.718)
Sorry, cannot reproduce/works like a charm:
https://github.com/xerx593/soq66415875
Uses configuration from src/main/resources/log4j2.xml.
Prints DEBUG log messages to:
console as to
${working_dir}/app-info.log
(according to configuration) and exits.
Tiny(iest) changes to original Post:
removed (redundant) <log4j2.version/> from pom.xml (2.13.3 - same version as managed by spring-boot-starter:2.4.2)
relative addressing of the log file.
Output:
[DEBUG] 03-01 05:20:38.923 [main] Log4j2Application - A DEBUG Message
[INFO ] 03-01 05:20:38.938 [main] Log4j2Application - An INFO Message
[WARN ] 03-01 05:20:38.938 [main] Log4j2Application - A WARN Message
[ERROR] 03-01 05:20:38.938 [main] Log4j2Application - An ERROR Message
[ERROR] 03-01 05:20:38.938 [main] Log4j2Application - Error Message Logged !!!
java.lang.NullPointerException: NullError
at com.example.demo.Log4j2Application.main(Log4j2Application.java:18) [classes/:?]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.2)
[INFO ] 03-01 05:20:39.839 [main] Log4j2Application - Starting Log4j2Application using Java 11.0.10 on rihanna with PID 9892 (D:\DEV\projects\soq66415875\target\classes started by xerx in D:\DEV\projects\soq66415875)
[DEBUG] 03-01 05:20:39.839 [main] Log4j2Application - Running with Spring Boot v2.4.2, Spring v5.3.3
[INFO ] 03-01 05:20:39.839 [main] Log4j2Application - No active profile set, falling back to default profiles: default
[DEBUG] 03-01 05:20:39.839 [main] SpringApplication - Loading source class com.example.demo.Log4j2Application
...
.... tons of debug messages, and finally:
...
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
[INFO ] 03-01 05:20:40.889 [main] Log4j2Application - Started Log4j2Application in 1.744 seconds (JVM running for 3.669)
[DEBUG] 03-01 05:20:40.904 [SpringContextShutdownHook] AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#54ec8cc9, started on Mon Mar 01 05:20:39 CET 2021
[DEBUG] 03-01 05:20:40.904 [SpringContextShutdownHook] AnnotationMBeanExporter - Unregistering JMX-exposed beans on shutdown
;) (or it is one/both of the tiny changes, or other "side effects")
I think both your problems arouse because you were not excluding the logging dependency from the spring-boot-starter-parent which you were including as the parent dependency. You need to exclude it from starter parent like:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
Your pom.xml was excluding it from spring-boot-starter instead.

Fat jar with Spring core and Spring jdbc

I have a Gradle project which uses Spring core and Spring JDBC and it runs succesfully if I do a Gradle run. The project does not run when I convert that into a fat jar.
I suspect that Spring configuration is not getting loaded before the main program is run. I use Gradle to build the fat jar which looks good. I have added pictures of the error and the fat jar. This is the error log.
C:\CGIADM\Utils\advhealthcheck>java -jar build\libs\advhealthcheck.jar
2019-09-13 16:38:55,625 main DEBUG null null initializing configuration XmlConfiguration[location=jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml]
2019-09-13 16:38:55,625 main DEBUG Installed 1 script engine
2019-09-13 16:38:55,828 main DEBUG Oracle Nashorn version: 1.8.0_151, language: ECMAScript, threading: Not Thread Safe, compile: true, names: [nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript], factory class: jdk.nashorn.api.scripting.NashornScriptEngineFactory
2019-09-13 16:38:55,828 main DEBUG PluginManager 'Core' found 117 plugins
2019-09-13 16:38:55,828 main DEBUG PluginManager 'Level' found 0 plugins
2019-09-13 16:38:55,828 main DEBUG Building Plugin[name=property, class=org.apache.logging.log4j.core.config.Property].
2019-09-13 16:38:55,844 main DEBUG PluginManager 'TypeConverter' found 26 plugins
2019-09-13 16:38:55,844 main DEBUG createProperty(name="pattern", value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [thread-id %T] %l - %msg%n")
2019-09-13 16:38:55,844 main DEBUG Building Plugin[name=property, class=org.apache.logging.log4j.core.config.Property].
2019-09-13 16:38:55,844 main DEBUG createProperty(name="basePath", value="./log")
2019-09-13 16:38:55,844 main DEBUG Building Plugin[name=properties, class=org.apache.logging.log4j.core.config.PropertiesPlugin].
2019-09-13 16:38:55,844 main DEBUG configureSubstitutor(={pattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [thread-id %T] %l - %msg%n, basePath=./log}, Configuration(jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml))
2019-09-13 16:38:55,844 main DEBUG PluginManager 'Lookup' found 13 plugins
2019-09-13 16:38:55,844 main DEBUG Building Plugin[name=Route, class=org.apache.logging.log4j.core.appender.routing.Route].
2019-09-13 16:38:55,860 main DEBUG createRoute(ref="null", key="${ctx:healthcheck}", Node=Route)
2019-09-13 16:38:55,860 main DEBUG Building Plugin[name=Route, class=org.apache.logging.log4j.core.appender.routing.Route].
2019-09-13 16:38:55,860 main DEBUG createRoute(ref="null", key="null", Node=Route)
2019-09-13 16:38:55,860 main DEBUG Building Plugin[name=Routes, class=org.apache.logging.log4j.core.appender.routing.Routes].
2019-09-13 16:38:55,860 main DEBUG Routes$Builder(Configuration(jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml), pattern="${ctx:healthcheck}", Script=null, ={Route(type=dynamic - type=Route key='${ctx:healthcheck}'), Route(type=dynamic - type=Route default)})
2019-09-13 16:38:55,860 main DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.routing.RoutingAppender].
2019-09-13 16:38:55,875 main DEBUG RoutingAppender$Builder(Script=null, Routes({Route(type=dynamic - type=Route key='${ctx:healthcheck}'),Route(type=dynamic - type=Route default)}), RewritePolicy=null, PurgePolicy=null, ignoreExceptions="null", Layout=null, name="Routing", Configuration(jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml), Filter=null, ={})
2019-09-13 16:38:55,875 main DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2019-09-13 16:38:55,875 main DEBUG PatternLayout$Builder(pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [thread-id %T] %l - %msg%n", PatternSelector=null, Configuration(jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2019-09-13 16:38:55,875 main DEBUG PluginManager 'Converter' found 44 plugins
2019-09-13 16:38:55,875 main DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.ConsoleAppender].
2019-09-13 16:38:55,891 main DEBUG ConsoleAppender$Builder(target="SYSTEM_OUT", follow="null", direct="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [thread-id %T] %l - %msg%n), name="console", Configuration(jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml), Filter=null, ={})
2019-09-13 16:38:55,891 main DEBUG Starting OutputStreamManager SYSTEM_OUT.false.false
2019-09-13 16:38:55,891 main DEBUG Building Plugin[name=appenders, class=org.apache.logging.log4j.core.config.AppendersPlugin].
2019-09-13 16:38:55,891 main DEBUG createAppenders(={Routing, console})
2019-09-13 16:38:55,891 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2019-09-13 16:38:55,891 main DEBUG createAppenderRef(ref="Routing", level="null", Filter=null)
2019-09-13 16:38:55,891 main DEBUG Building Plugin[name=root, class=org.apache.logging.log4j.core.config.LoggerConfig$RootLogger].
2019-09-13 16:38:55,891 main DEBUG createLogger(additivity="null", level="INFO", includeLocation="null", ={Routing}, ={}, Configuration(jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml), Filter=null)
2019-09-13 16:38:55,891 main DEBUG Building Plugin[name=loggers, class=org.apache.logging.log4j.core.config.LoggersPlugin].
2019-09-13 16:38:55,891 main DEBUG createLoggers(={root})
2019-09-13 16:38:55,891 main DEBUG Configuration XmlConfiguration[location=jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml] initialized
2019-09-13 16:38:55,891 main DEBUG Starting configuration XmlConfiguration[location=jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml]
2019-09-13 16:38:55,891 main DEBUG Started configuration XmlConfiguration[location=jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml] OK.
2019-09-13 16:38:55,891 main DEBUG Shutting down OutputStreamManager SYSTEM_OUT.false.false-1
2019-09-13 16:38:55,891 main DEBUG Shut down OutputStreamManager SYSTEM_OUT.false.false-1, all resources released: true
2019-09-13 16:38:55,907 main DEBUG Appender DefaultConsole-1 stopped with status true
2019-09-13 16:38:55,907 main DEBUG Stopped org.apache.logging.log4j.core.config.DefaultConfiguration#48533e64 OK
2019-09-13 16:38:55,938 main DEBUG Registering MBean org.apache.logging.log4j2:type=5c647e05
2019-09-13 16:38:55,938 main DEBUG Registering MBean org.apache.logging.log4j2:type=5c647e05,component=StatusLogger
2019-09-13 16:38:55,938 main DEBUG Registering MBean org.apache.logging.log4j2:type=5c647e05,component=ContextSelector
2019-09-13 16:38:55,938 main DEBUG Registering MBean org.apache.logging.log4j2:type=5c647e05,component=Loggers,name=
2019-09-13 16:38:55,938 main DEBUG Registering MBean org.apache.logging.log4j2:type=5c647e05,component=Appenders,name=Routing
2019-09-13 16:38:55,938 main DEBUG Registering MBean org.apache.logging.log4j2:type=5c647e05,component=Appenders,name=console
2019-09-13 16:38:55,938 main DEBUG org.apache.logging.log4j.core.util.SystemClock does not support precise timestamps.
2019-09-13 16:38:55,938 main DEBUG Reconfiguration complete for context[name=5c647e05] at URI jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml (org.apache.logging.log4j.core.LoggerContext#74235045) with optional ClassLoader: null
2019-09-13 16:38:55,938 main DEBUG Shutdown hook enabled. Registering a new one.
2019-09-13 16:38:55,953 main DEBUG LoggerContext[name=5c647e05, org.apache.logging.log4j.core.LoggerContext#74235045] started OK.
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.IllegalStateException: Cannot load configuration class: adv.healthcheck.conn.SpringJdbcConfig
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:404)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory(ConfigurationClassPostProcessor.java:249)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:283)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:127)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:687)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:525)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at adv.tasks.AdvHealthCheckTaskProcessor.addTaskToList(AdvHealthCheckTaskProcessor.java:71)
at adv.tasks.AdvHealthCheckTaskProcessor.runMainHealthCheckProcessor(AdvHealthCheckTaskProcessor.java:36)
at adv.tasks.AdvHealthCheckTaskProcessor.main(AdvHealthCheckTaskProcessor.java:31)
Caused by: java.lang.IllegalStateException: Unable to load cache item
at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:79)
at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:291)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:480)
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:337)
at org.springframework.context.annotation.ConfigurationClassEnhancer.createClass(ConfigurationClassEnhancer.java:138)
at org.springframework.context.annotation.ConfigurationClassEnhancer.enhance(ConfigurationClassEnhancer.java:110)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:394)
... 9 more
Caused by: java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:467)
at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:336)
at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:492)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)
at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54)
at java.util.concurrent.FutureTask.run(Unknown Source)
at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61)
... 17 more
Caused by: java.util.NoSuchElementException: get() on Left
at io.vavr.control.Either$Left.get(Either.java:935)
at adv.healthcheck.conn.SpringJdbcConfig.<clinit>(SpringJdbcConfig.java:20)
... 27 more
2019-09-13 16:38:56,203 pool-1-thread-1 DEBUG Stopping LoggerContext[name=5c647e05, org.apache.logging.log4j.core.LoggerContext#74235045]
2019-09-13 16:38:56,203 pool-1-thread-1 DEBUG Stopping LoggerContext[name=5c647e05, org.apache.logging.log4j.core.LoggerContext#74235045]...
2019-09-13 16:38:56,219 pool-1-thread-1 DEBUG Shutting down OutputStreamManager SYSTEM_OUT.false.false
2019-09-13 16:38:56,219 pool-1-thread-1 DEBUG Shut down OutputStreamManager SYSTEM_OUT.false.false, all resources released: true
2019-09-13 16:38:56,219 pool-1-thread-1 DEBUG Appender console stopped with status true
2019-09-13 16:38:56,219 pool-1-thread-1 DEBUG Stopped XmlConfiguration[location=jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml] OK
2019-09-13 16:38:56,219 pool-1-thread-1 DEBUG Stopped LoggerContext[name=5c647e05, org.apache.logging.log4j.core.LoggerContext#74235045] with status true
import static adv.util.AdvHealthCheckFileUtils.loadAppConfigFile;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
#Configuration
public class SpringJdbcConfig {
private static String DRIVER_CLASS_NAME = "driverClassName";
private static String JDBC_URL = "jdbcurl";
private static String SCHEMA_USERNAME = "userName";
private static String SCHEMA_PASSWORD = "password";
static Properties props;
static {
props = loadAppConfigFile().get();
}
#Bean
public DataSource dataSource() {
return myJdbcDataSource();
}
// #Bean
public DataSource myJdbcDataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(props.getProperty(DRIVER_CLASS_NAME));
dataSource.setUrl(props.getProperty(JDBC_URL));
dataSource.setUsername(props.getProperty(SCHEMA_USERNAME));
dataSource.setPassword(props.getProperty(SCHEMA_PASSWORD));
return dataSource;
}
}

How to turn off debug log messages in spring boot

I read in spring boot docs (https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html)
you can also specify debug=true in your application.properties"
So I guess I can turn off the debug logs by adding debug=false in application.properties. I did it but unfortunately, it didn't work. Then I read in the same doc
The logging system is initialized early in the application lifecycle and as such logging properties will not be found in property files loaded via #PropertySource annotations"
and
"Since logging is initialized before the ApplicationContext is created, it isn’t possible to control logging from #PropertySources in Spring #Configuration files"
and
"When possible we recommend that you use the -spring variants for your logging configuration" so I added a file named log4j-spring.properties in src/main/resources.
In such file, I added debug=false (only this line and nothing else) but I am still seeing all "current date" [main] DEBUG ... messages. So, my question is how can I turn off the debug messages in my Spring Boot Application as I will deploy to the application to production. Is there a recommended way to reach this via maven?
Added in Feb 12th
The two main methods:
1)By using AnnotationConfigApplicationContext:
public class DemoAppNoBoot {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
BatchConfiguration.class);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("job");
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Snippet output:
08:26:18.713 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
08:26:18.744 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
08:26:18.744 [main] DEBUG o.s.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
08:26:18.947 [main] INFO o.s.c.a.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#532760d8: startup date [Fri Feb 12 08:26:18 CST 2016]; root of context hierarchy
08:26:18.947 [main] DEBUG o.s.c.a.AnnotationConfigApplicationContext - Bean factory for org.springframework.context.annotation.AnnotationConfigApplicationContext#532760d8: org.springframework.beans.factory.support.DefaultListableBeanFactory#50b494a6: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,batchConfiguration]; root of factory hierarchy
08:26:18.979 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean
...
08:26:32.560 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
08:26:32.560 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalScheduledAnnotationProcessor'
08:26:32.560 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor'
08:26:32.560 [main] DEBUG o.s.s.a.ScheduledAnnotationBeanPostProcessor - Could not find default TaskScheduler bean
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.scheduling.TaskScheduler] is defined at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:372) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:332) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
...
08:26:33.529 [pool-1-thread-1] DEBUG o.s.jdbc.core.JdbcTemplate - Executing prepared SQL update
08:26:33.529 [pool-1-thread-1] DEBUG o.s.jdbc.core.JdbcTemplate - Executing prepared SQL statement [UPDATE BATCH_JOB_EXECUTION set START_TIME = ?, END_TIME = ?, STATUS = ?, EXIT_CODE = ?, EXIT_MESSAGE = ?, VERSION = ?, CREATE_TIME = ?, LAST_UPDATED = ? where JOB_EXECUTION_ID = ? and VERSION = ?]
08:26:33.529 [pool-1-thread-1] DEBUG o.s.jdbc.core.JdbcTemplate - SQL update affected 1 rows
08:26:33.545 [pool-1-thread-1] DEBUG o.s.j.d.DataSourceTransactionManager - Initiating transaction commit
08:26:33.545 [pool-1-thread-1] DEBUG o.s.j.d.DataSourceTransactionManager - Committing JDBC transaction on Connection [org.hsqldb.jdbc.JDBCConnection#33bbce9c]
08:26:33.545 [pool-1-thread-1] DEBUG o.s.j.d.DataSourceTransactionManager - Releasing JDBC Connection [org.hsqldb.jdbc.JDBCConnection#33bbce9c] after transaction
08:26:33.545 [pool-1-thread-1] DEBUG o.s.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
08:26:33.545 [pool-1-thread-1] INFO o.s.b.c.l.support.SimpleJobLauncher - Job: [SimpleJob: [name=job1]] completed with the following parameters: [{}] and the following status: [COMPLETED]
Main method with SpringApplication.run
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(BatchConfiguration.class, args);
}
}
Entire output:
: Spring Boot :: (v1.3.1.RELEASE)
2016-02-12 08:02:36.145 INFO 12172 --- [ main] com.example.DemoApplication : Starting DemoApplication on GH-VDIKCISV252 with PID 12172 (C:\STS\wsRestTemplate\demo\target\classes started by e049447 in C:\STS\wsRestTemplate\demo)
2016-02-12 08:02:36.145 INFO 12172 --- [ main] com.example.DemoApplication : No active profile set, falling back to default profiles: default
2016-02-12 08:02:36.473 INFO 12172 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#4e4aea35: startup date [Fri Feb 12 08:02:36 CST 2016]; root of context hierarchy
2016-02-12 08:02:42.176 WARN 12172 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method ScopeConfiguration.stepScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details.
2016-02-12 08:02:42.349 WARN 12172 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method ScopeConfiguration.jobScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details.
2016-02-12 08:02:42.724 INFO 12172 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Starting embedded database: url='jdbc:hsqldb:mem:testdb', username='sa'
2016-02-12 08:02:43.802 WARN 12172 --- [ main] o.s.b.c.l.AbstractListenerFactoryBean : org.springframework.batch.item.ItemReader is an interface. The implementing class will not be queried for annotation based listener configurations. If using #StepScope on a #Bean method, be sure to return the implementing class so listner annotations can be used.
2016-02-12 08:02:44.990 INFO 12172 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql]
2016-02-12 08:02:45.179 INFO 12172 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql] in 189 ms.
2016-02-12 08:02:46.804 INFO 12172 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-02-12 08:02:46.868 INFO 12172 --- [ main] o.s.b.a.b.JobLauncherCommandLineRunner : Running default command line with: []
2016-02-12 08:02:46.962 INFO 12172 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: HSQL
2016-02-12 08:02:47.040 INFO 12172 --- [pool-2-thread-1] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: HSQL
2016-02-12 08:02:47.243 INFO 12172 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2016-02-12 08:02:47.259 INFO 12172 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2016-02-12 08:02:47.321 INFO 12172 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] launched with the following parameters: [{run.id=1}]
2016-02-12 08:02:47.368 INFO 12172 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [step1]
2016-02-12 08:02:47.400 INFO 12172 --- [ main] com.example.CustomItemReader : read method - collecting the MYAPP2 out file names
2016-02-12 08:02:47.525 INFO 12172 --- [ main] com.example.CustomItemReader : read method - no file found
2016-02-12 08:02:47.556 INFO 12172 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] completed with the following parameters: [{run.id=1}] and the following status: [COMPLETED]
2016-02-12 08:02:47.556 INFO 12172 --- [ main] com.example.DemoApplication : Started DemoApplication in 12.1 seconds (JVM running for 13.405)
2016-02-12 08:02:47.556 INFO 12172 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] launched with the following parameters: [{}]
2016-02-12 08:02:47.618 INFO 12172 --- [pool-2-thread-1] o.s.batch.core.job.SimpleStepHandler : Executing step: [step1]
2016-02-12 08:02:47.634 INFO 12172 --- [pool-2-thread-1] com.example.CustomItemReader : read method - collecting the MYAPP2 out file names
2016-02-12 08:02:47.634 INFO 12172 --- [pool-2-thread-1] com.example.CustomItemReader : read method - no file found
2016-02-12 08:02:47.650 INFO 12172 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] completed with the following parameters: [{}] and the following status: [COMPLETED]
BatchConfiguration class
#Configuration
#ComponentScan("com.example")
#EnableBatchProcessing
#EnableAutoConfiguration
#EnableScheduling
#PropertySource("config.properties")
public class BatchConfiguration {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Bean
public Step step1(ItemReader<String> reader,
ItemProcessor<String, String> processor, ItemWriter<String> writer) {
return stepBuilderFactory.get("step1").<String, String> chunk(1) .reader(reader).processor(processor).writer(writer)
.allowStartIfComplete(true).build();
}
//I took out the rest of BatchConfiguration class
Application.properties (only one line)
logging.level.*=OFF
P.S. I will not show config.properties because it only contains several property names with path settup used in business logic
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<spring.batch.version>3.0.6.RELEASE</spring.batch.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.example.DemoAppNoBoot</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<goals>install</goals>
<preparationGoals>install</preparationGoals>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.example.DemoAppNoBoot</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
Maven Dependencies (the relevant ones for my doubt):
logback-classic-1.1.3.jar
logback-core-1.1.3.jar
slf4j-api-1.7.13.jar
log4j-over-slf4j-1.7.13.jar
In application.properties you can add ‘logging.level.*=LEVEL’ where ‘LEVEL’ is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF. * is responsible for package/class.
For example
logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
This means that root logger has WARN level.
org.springframework.web is on DEBUG level, but all hibernates files are logged only ERROR.
In your case you must set logging.level.root on one of level from INFO, WARN, ERROR,FATAL or OFF to turn off all logging.
See https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html#boot-features-custom-log-levels
While using Spring Rest Docs with SpringMockMVC with testLogging.showStandardStreams set to true in Gradle, Spring cluttered the console with info & debug logs. I had to use Mkyong's solution where in a logback-test.xml in src/test/resources needs to be created on top of the chosen solution here. Use log-level OFF, ERROR, WARN, DEBUG
logback-test.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<logger name="org.springframework" level="ERROR"/>
</configuration>
in addition to a log4j.properties or log4j.xml file you will need all three of these entries in your maven pom.xml... adding the log4j-acl artifact instantly fixed the problem for me. it routes apache-commons-logging entries from commons logging over to log4j
I'm not sure how you would go about this in grunt but the bridge is what you need.
<!-- Log4J -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jcl</artifactId>
<version>${log4j.version}</version>
</dependency>
Simply add these two lines to you app main:
Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.ERROR);
The necessary import are:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.slf4j.LoggerFactory;
I am using XML configured Log4j2 and Spring Boot. For me, I needed to specify the logging subpackage also, so inside the <Loggers> block:
<Logger name="org.springframework.boot.autoconfigure.logging" level="error" />
You can also use bellow pattern to see the neat logging results in Console.
logging.pattern.console=%clr(%d{yy-MM-dd E HH:mm:ss.SSS}){blue} %clr(%-5p) %clr(%logger{0}){blue} %clr(%m){faint}%n
Click Breakpoints icon and untick checkBox. After Done Re-Run again

Resources