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!
Related
"Hikari Pool-1 - Connection is not available, request timed out after 30004ms." exception occurs only on the development server.
I spent a lot of time trying to find this problem, but I couldn't. For the first time in my life, I'm posting a question on stackoverflow.Please let me know if there is anything lacking in the question.
For your understanding, I have placed an example source code on GitHub.
I included the DDL Query used in the example below the resource folder and the log file (dev-log.out) on the actual development server.
I wrote down what I wanted to ask you at the bottom.
The requirements I am trying to implement are as follows.
Put the data from the source table into the target table.
If an exception occurs in the process of 1), the transaction is rolled back and the corresponding exception information is loaded on the log table.
To meet this requirement, I declared #Transactional to a service class (DemoService class in the example) that performs 1).
#RequiredArgsConstructor
#Service
public class DemoService {
private final DemoRepository repository;
#Transactional
#Logging
public void run() {
List<Integer> ids = repository.select(); //select from source table
for (Integer id : ids) {
repository.insert(id); //insert into target table
//An exception was made intentionally to roll back test
if (id == 1) {
throw new RuntimeException("exception~~");
}
}
}
}
And I wrote Aop using #Aspect (LoggingAspect in the example) to load exception information into the table. And I gave the REQUIRES_NEW option because the transaction loading exception information should be committed separately from the transaction used in 1).
#RequiredArgsConstructor
#Slf4j
#Component
#Aspect
public class LoggingAspect {
private final LoggingService loggingService;
#AfterThrowing(value = "#annotation(com.example.dbcpquestion.logging.Logging)", throwing = "ex")
public void doLog(JoinPoint joinPoint, Exception ex) throws Throwable {
log.error("-----------------------------------------");
int cnt = loggingService.logging();
log.error("cnt={}", cnt);
log.error("-----------------------------------------");
}
}
#RequiredArgsConstructor
#Service
public class LoggingService {
private final LoggingRepository repository;
#Transactional(propagation = Propagation.REQUIRES_NEW)
public int logging() {
return repository.save(); //insert exception info into log table
}
}
I know that if an exception occurs while performing 1) logic, at least two connections are required. (Transactions that work to move data from the Source table to the Target table that will eventually be rolled back, and transactions that load exception information into the log table)
The problem is!
The logic (1, 2) above works fine on the local PC, but when deployed to the development server, the exception "Hikari Pool-1 - Connection is not available, request timed out after 30004ms."
The strangest thing happens intermittently... (crazy)
Here's the Hikari setup log.
[2022-10-06 18:46:00.724] [DEBUG] [main] [HikariConfig ]- HikariPool-1 - configuration:
[2022-10-06 18:46:00.730] [DEBUG] [main] [HikariConfig ]- allowPoolSuspension................................false
[2022-10-06 18:46:00.730] [DEBUG] [main] [HikariConfig ]- autoCommit................................true
[2022-10-06 18:46:00.730] [DEBUG] [main] [HikariConfig ]- catalog................................none
[2022-10-06 18:46:00.730] [DEBUG] [main] [HikariConfig ]- connectionInitSql................................none
[2022-10-06 18:46:00.731] [DEBUG] [main] [HikariConfig ]- connectionTestQuery................................none
[2022-10-06 18:46:00.731] [DEBUG] [main] [HikariConfig ]- connectionTimeout................................30000
[2022-10-06 18:46:00.731] [DEBUG] [main] [HikariConfig ]- dataSource................................none
[2022-10-06 18:46:00.732] [DEBUG] [main] [HikariConfig ]- dataSourceClassName................................none
[2022-10-06 18:46:00.732] [DEBUG] [main] [HikariConfig ]- dataSourceJNDI................................none
[2022-10-06 18:46:00.734] [DEBUG] [main] [HikariConfig ]- dataSourceProperties................................{password=<masked>}
[2022-10-06 18:46:00.734] [DEBUG] [main] [HikariConfig ]- driverClassName................................"oracle.jdbc.OracleDriver"
[2022-10-06 18:46:00.734] [DEBUG] [main] [HikariConfig ]- exceptionOverrideClassName................................none
[2022-10-06 18:46:00.734] [DEBUG] [main] [HikariConfig ]- healthCheckProperties................................{}
[2022-10-06 18:46:00.734] [DEBUG] [main] [HikariConfig ]- healthCheckRegistry................................none
[2022-10-06 18:46:00.735] [DEBUG] [main] [HikariConfig ]- idleTimeout................................600000
[2022-10-06 18:46:00.735] [DEBUG] [main] [HikariConfig ]- initializationFailTimeout................................1
[2022-10-06 18:46:00.735] [DEBUG] [main] [HikariConfig ]- isolateInternalQueries................................false
[2022-10-06 18:46:00.735] [DEBUG] [main] [HikariConfig ]- jdbcUrl................................[Cleared for security reasons.]
[2022-10-06 18:46:00.736] [DEBUG] [main] [HikariConfig ]- keepaliveTime................................0
[2022-10-06 18:46:00.736] [DEBUG] [main] [HikariConfig ]- leakDetectionThreshold................................2000
[2022-10-06 18:46:00.736] [DEBUG] [main] [HikariConfig ]- maxLifetime................................1800000
[2022-10-06 18:46:00.736] [DEBUG] [main] [HikariConfig ]- maximumPoolSize................................3
[2022-10-06 18:46:00.737] [DEBUG] [main] [HikariConfig ]- metricRegistry................................none
[2022-10-06 18:46:00.737] [DEBUG] [main] [HikariConfig ]- metricsTrackerFactory................................none
[2022-10-06 18:46:00.737] [DEBUG] [main] [HikariConfig ]- minimumIdle................................3
[2022-10-06 18:46:00.737] [DEBUG] [main] [HikariConfig ]- password................................<masked>
[2022-10-06 18:46:00.737] [DEBUG] [main] [HikariConfig ]- poolName................................"HikariPool-1"
[2022-10-06 18:46:00.738] [DEBUG] [main] [HikariConfig ]- readOnly................................false
[2022-10-06 18:46:00.738] [DEBUG] [main] [HikariConfig ]- registerMbeans................................false
[2022-10-06 18:46:00.738] [DEBUG] [main] [HikariConfig ]- scheduledExecutor................................none
[2022-10-06 18:46:00.738] [DEBUG] [main] [HikariConfig ]- schema................................none
[2022-10-06 18:46:00.739] [DEBUG] [main] [HikariConfig ]- threadFactory................................internal
[2022-10-06 18:46:00.739] [DEBUG] [main] [HikariConfig ]- transactionIsolation................................default
[2022-10-06 18:46:00.739] [DEBUG] [main] [HikariConfig ]- username................................[Cleared for security reasons.]
[2022-10-06 18:46:00.739] [DEBUG] [main] [HikariConfig ]- validationTimeout................................5000
[2022-10-06 18:46:00.739] [INFO ] [main] [HikariDataSource ]- HikariPool-1 - Starting...
[2022-10-06 18:46:02.249] [DEBUG] [main] [HikariPool ]- HikariPool-1 - Added connection oracle.jdbc.driver.T4CConnection#1fc684e
[2022-10-06 18:46:02.252] [INFO ] [main] [HikariDataSource ]- HikariPool-1 - Start completed.
[2022-10-06 18:46:02.288] [INFO ] [main] [DemoService ]- [select]..................
[2022-10-06 18:46:02.361] [DEBUG] [HikariPool-1 housekeeper] [HikariPool ]- HikariPool-1 - Pool stats (total=1, active=1, idle=0, waiting=0)
[2022-10-06 18:46:02.369] [DEBUG] [HikariPool-1 connection adder] [PoolBase ]- HikariPool-1 - Failed to create/setup connection: null
[2022-10-06 18:46:02.390] [DEBUG] [HikariPool-1 connection adder] [HikariPool ]- HikariPool-1 - Cannot acquire connection from data source
java.lang.NullPointerException: null
Yaml file settings.
Logging level has been set to DEBUG.
Hikari's maximum-pool-size is set to 3. As far as I know, I can set it to 2, but...I added one more connection
I also set leak-detection-threshold to look at connection leak.
As an example, url was specified as localhost, but the URL is actually specified as an IP address, not localhost. Both local profiles and dev profiles have the same DB connection information.
spring:
datasource:
username: dbcp
password: dbcp
driver-class-name: oracle.jdbc.OracleDriver
hikari:
maximum-pool-size: 3
leak-detection-threshold: 2000
logging:
pattern:
console: "[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] [%thread] [%-25logger{0}]- %msg%n"
level:
'[com.zaxxer.hikari]': trace
'[com.zaxxer.hikari.HikariConfig]': debug
---
spring:
config:
activate:
on-profile: local
datasource:
url: jdbc:oracle:thin:#localhost:1521:orcl
#As an example, url was specified as localhost, but the URL is actually specified as an IP address, not localhost. Both local profiles and dev profiles have the same DB connection information.
---
spring:
config:
activate:
on-profile: dev
datasource:
url: jdbc:oracle:thin:#localhost:1521:orcl
The entire log.(Omit part of the log because of the number of characters.)
[2022-10-06 18:46:02.361] [DEBUG] [HikariPool-1 housekeeper] [HikariPool ]- HikariPool-1 - Pool stats (total=1, active=1, idle=0, waiting=0)
[2022-10-06 18:46:02.369] [DEBUG] [HikariPool-1 connection adder] [PoolBase ]- HikariPool-1 - Failed to create/setup connection: null
[2022-10-06 18:46:02.390] [DEBUG] [HikariPool-1 connection adder] [HikariPool ]- HikariPool-1 - Cannot acquire connection from data source
java.lang.NullPointerException: null
at java.base/java.lang.StringCoding.encode(StringCoding.java:652)
at java.base/java.lang.String.getBytes(String.java:982)
at java.base/java.lang.ProcessEnvironment$Variable.valueOfQueryOnly(ProcessEnvironment.java:166)
at java.base/java.lang.ProcessEnvironment$Variable.valueOfQueryOnly(ProcessEnvironment.java:162)
at java.base/java.lang.ProcessEnvironment$StringEnvironment.get(ProcessEnvironment.java:239)
at java.base/java.lang.ProcessEnvironment$StringEnvironment.get(ProcessEnvironment.java:221)
at java.base/java.util.Collections$UnmodifiableMap.get(Collections.java:1454)
at java.base/java.lang.ProcessEnvironment.getenv(ProcessEnvironment.java:85)
at java.base/java.lang.System.getenv(System.java:1001)
at oracle.jdbc.driver.PhysicalConnection.lambda$getTnsAdminFromEnv$4(PhysicalConnection.java:10990)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at oracle.jdbc.driver.PhysicalConnection.getTnsAdminFromEnv(PhysicalConnection.java:10987)
at oracle.jdbc.driver.PhysicalConnection.readConnectionProperties(PhysicalConnection.java:1427)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:941)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:926)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:542)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:69)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:728)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:649)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476)
at com.zaxxer.hikari.pool.HikariPool.access$100(HikariPool.java:71)
at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:726)
at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:712)
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:834)
[2022-10-06 18:46:02.660] [DEBUG] [HikariPool-1 connection adder] [HikariPool ]- HikariPool-1 - Cannot acquire connection from data source
java.lang.NullPointerException: null
at java.base/java.lang.StringCoding.encode(StringCoding.java:652)
at java.base/java.lang.String.getBytes(String.java:982)
at java.base/java.lang.ProcessEnvironment$Variable.valueOfQueryOnly(ProcessEnvironment.java:166)
at java.base/java.lang.ProcessEnvironment$Variable.valueOfQueryOnly(ProcessEnvironment.java:162)
at java.base/java.lang.ProcessEnvironment$StringEnvironment.get(ProcessEnvironment.java:239)
/////Omit part of the log because of the number of characters.
[2022-10-06 18:46:02.928] [ERROR] [main] [LoggingAspect ]- -----------------------------------------
[2022-10-06 18:46:03.055] [DEBUG] [HikariPool-1 connection adder] [HikariPool ]- HikariPool-1 - Cannot acquire connection from data source
java.lang.NullPointerException: null
at java.base/java.lang.StringCoding.encode(StringCoding.java:652)
/////Omit part of the log because of the number of characters.
[2022-10-06 18:46:03.624] [DEBUG] [HikariPool-1 connection adder] [HikariPool ]- HikariPool-1 - Cannot acquire connection from data source
java.lang.NullPointerException: null
at java.base/java.lang.StringCoding.encode(StringCoding.java:652)
/////Omit part of the log because of the number of characters.
[2022-10-06 18:46:04.278] [WARN ] [HikariPool-1 housekeeper] [ProxyLeakTask ]- Connection leak detection triggered for oracle.jdbc.driver.T4CConnection#1fc684e on thread main, stack trace follows
java.lang.Exception: Apparent connection leak detected
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:128)
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:265)
/////Omit part of the log because of the number of characters.
[2022-10-06 18:46:04.475] [DEBUG] [HikariPool-1 connection adder] [HikariPool ]- HikariPool-1 - Cannot acquire connection from data source
java.lang.NullPointerException: null
at java.base/java.lang.StringCoding.encode(StringCoding.java:652)
/////Omit part of the log because of the number of characters.
[2022-10-06 18:46:05.745] [DEBUG] [HikariPool-1 connection adder] [HikariPool ]- HikariPool-1 - Cannot acquire connection from data source
java.lang.NullPointerException: null
at java.base/java.lang.StringCoding.encode(StringCoding.java:652)
[2022-10-06 18:46:32.371] [DEBUG] [HikariPool-1 housekeeper] [HikariPool ]- HikariPool-1 - Pool stats (total=1, active=1, idle=0, waiting=1)
[2022-10-06 18:46:32.371] [DEBUG] [HikariPool-1 housekeeper] [HikariPool ]- HikariPool-1 - Fill pool skipped, pool is at sufficient level.
[2022-10-06 18:46:32.931] [DEBUG] [main] [HikariPool ]- HikariPool-1 - Timeout failure stats (total=1, active=1, idle=0, waiting=0)
[2022-10-06 18:46:32.955] [INFO ] [main] [ProxyLeakTask ]- Previously reported leaked connection oracle.jdbc.driver.T4CConnection#1fc684e on thread main was returned to the pool (unleaked)
[2022-10-06 18:46:32.961] [INFO ] [main] [ConditionEvaluationReportLoggingListener]-
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
[2022-10-06 18:46:33.010] [ERROR] [main] [SpringApplication ]- Application run failed
java.lang.IllegalStateException: Failed to execute ApplicationRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:776)
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:763)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1317)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306)
at com.springboot.example.ExampleApplication.main(ExampleApplication.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.loader.MainMethodRunner.run(MainMethodRunner.java:49)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:108)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:58)
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88)
Caused by: org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30004ms.
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:309)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.startTransaction(AbstractPlatformTransactionManager.java:400)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.handleExistingTransaction(AbstractPlatformTransactionManager.java:434)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:352)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:595)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:382)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708)
at com.springboot.example.logging.LoggingService$$EnhancerBySpringCGLIB$$f2e4eeed.logging(<generated>)
at com.springboot.example.logging.LoggingAspect.doLog(LoggingAspect.java:23)
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.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:634)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:617)
at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:68)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708)
at com.springboot.example.DemoService$$EnhancerBySpringCGLIB$$3b65fd43.run(<generated>)
at com.springboot.example.ExampleApplication.lambda$applicationRunner$0(ExampleApplication.java:27)
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:773)
... 13 common frames omitted
Caused by: java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30004ms.
at com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:696)
at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:197)
at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:162)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:128)
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:265)
... 45 common frames omitted
[2022-10-06 18:46:33.020] [INFO ] [main] [HikariDataSource ]- HikariPool-1 - Shutdown initiated...
[2022-10-06 18:46:33.020] [DEBUG] [main] [HikariPool ]- HikariPool-1 - Before shutdown stats (total=1, active=0, idle=1, waiting=0)
[2022-10-06 18:46:33.023] [DEBUG] [HikariPool-1 connection closer] [PoolBase ]- HikariPool-1 - Closing connection oracle.jdbc.driver.T4CConnection#1fc684e: (connection evicted)
[2022-10-06 18:46:40.826] [DEBUG] [main] [HikariPool ]- HikariPool-1 - After shutdown stats (total=0, active=0, idle=0, waiting=0)
[2022-10-06 18:46:40.826] [INFO ] [main] [HikariDataSource ]- HikariPool-1 - Shutdown completed.
What I checked to solve this problem is as follows.
I checked the settings of the Oracle DB server.
'IDLE_TIME' is set much longer than Hikari maxLifeTime.
'CONNECT_TIME' is unlimit.
We excluded the setting to load all spring bean into Lazy.
The actual project uses Mybatis, but if you look at what happens when you use JdbcTemplate, as in the example...I don't think Mybatis or Lazy loading is the cause.
The local DB and the DB used by the development server are all the same.
I confirmed that there were three sessions connected from Oracle when the problem did not occur and that there was one session connected when the exception occurred. From this, I expected that the connection itself would not be obtained.
What I'm curious about is as follows.
When logging level is set to DEBUG, the message 'Hikari Pool-1 - Canot acquisition connection from data source' appears frequently. Is it related to this part? (And what does this message mean?) Is the network unstable?)
If you look at the entire log,
[2022-10-06 18:46:32.371] [DEBUG] [HikariPool-1 housekeeper] [HikariPool ]- HikariPool-1 - Pool stats (total=1, active=1, idle=0, waiting=1)
[2022-10-06 18:46:32.371] [DEBUG] [HikariPool-1 housekeeper] [HikariPool ]- HikariPool-1 - Fill pool skipped, pool is at sufficient level.
[2022-10-06 18:46:32.931] [DEBUG] [main] [HikariPool ]- HikariPool-1 - Timeout failure stats (total=1, active=1, idle=0, waiting=0)
~~~~
Caused by: org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30004ms.
This log remains. Can I say that it was 'waiting=1' and then changed to 'waiting=0' because a timeout exception occurred...?
Is it because you didn't get the connection?
Can't I run the application after the connection pool has three connections set to maximum-pool-size? As far as I know, Hikari's separate threads are out of control because they serve to get Connection.
I'd really appreciate your help.
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;
}
}
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.
Have some Spring Boot Integrationtests, e.g.:
#RunWith(SpringRunner.class)
#SpringBootTest
public class SupplierToSapInvoiceIntegrationTest {
...
}
All tests are successful when running locally, but on bamboo all tests fail. The Log says:
build 05-Mai-2017 15:20:46 2017-05-05 15:20:46.943 INFO 6556 ---
[ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Neither
#ContextConfiguration nor #ContextHierarchy found for test class
[com.odm.integration.SupplierToSapIntegrationTest], using
SpringBootContextLoader build 05-Mai-2017 15:20:46 2017-05-05
15:20:46.943 INFO 6556 --- [ Test worker]
o.s.t.c.support.AbstractContextLoader : Could not detect default
resource locations for test class
[com.odm.integration.SupplierToSapIntegrationTest]: no resource found
for suffixes {-context.xml, Context.groovy}. build 05-Mai-2017
15:20:46 2017-05-05 15:20:46.943 INFO 6556 --- [ Test worker]
t.c.s.AnnotationConfigContextLoaderUtils : Could not detect default
configuration classes for test class
[com.odm.integration.SupplierToSapIntegrationTest]:
SupplierToSapIntegrationTest does not declare any static, non-private,
non-final, nested classes annotated with #Configuration.
build 05-Mai-2017 15:20:46 2017-05-05 15:20:46.943 INFO 6556 ---
[ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Found
#SpringBootConfiguration com.odm.OdmBackendApplication for test class
com.odm.integration.SupplierToSapIntegrationTest build 05-Mai-2017
15:20:46 2017-05-05 15:20:46.943 INFO 6556 --- [ Test worker]
.b.t.c.SpringBootTestContextBootstrapper : Loaded default
TestExecutionListener class names from location
[META-INF/spring.factories]:
[org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener,
org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener,
org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener,
org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener,
org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener,
org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener,
org.springframework.test.context.web.ServletTestExecutionListener,
org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener,
org.springframework.test.context.support.DependencyInjectionTestExecutionListener,
org.springframework.test.context.support.DirtiesContextTestExecutionListener,
org.springframework.test.context.transaction.TransactionalTestExecutionListener,
org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
build 05-Mai-2017 15:20:46 2017-05-05 15:20:46.943 INFO 6556 ---
[ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Could not
instantiate TestExecutionListener
[org.springframework.test.context.web.ServletTestExecutionListener].
Specify custom listener classes or make the default listener classes
(and their required dependencies) available. Offending class:
[javax/servlet/ServletContext] build 05-Mai-2017 15:20:46
2017-05-05 15:20:46.943 INFO 6556 --- [ Test worker]
.b.t.c.SpringBootTestContextBootstrapper : Using
TestExecutionListeners:
[org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#7beec6bf,
org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener#79dadc3e,
org.springframework.test.context.support.DirtiesContextTestExecutionListener#128f4f9c,
org.springframework.test.context.transaction.TransactionalTestExecutionListener#dad26fb,
org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#fbd2cf,
org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener#2fefc5c2,
org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#47749c0c,
org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener#230af0e7,
org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#7db923e3,
org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener#2c293843,
org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener#4f5e5536]
Any idea, help? THX!!
I am rather new to JHipster and I followed their instructions in order to create a new app.
The app was created, imported into STS as a Maven project and I updated it.
However as soon as I try to start it via the Boot Dashboard I get this output :
2016-12-07 16:43:14.887 INFO 6396 --- [ restartedMain] com.mycompany.myapp.MdcApp : Starting MdcApp on PC981 with PID 6396 (C:\Users\lvuillaume\Desktop\mdc\target\classes started by lvuillaume in C:\Users\lvuillaume\Desktop\mdc)
2016-12-07 16:43:14.890 DEBUG 6396 --- [ restartedMain] com.mycompany.myapp.MdcApp : Running with Spring Boot v1.4.2.RELEASE, Spring v4.3.4.RELEASE
2016-12-07 16:43:14.891 INFO 6396 --- [ restartedMain] com.mycompany.myapp.MdcApp : The following profiles are active: swagger,dev
2016-12-07 16:43:14.972 DEBUG 6396 --- [kground-preinit] org.jboss.logging : Logging Provider: org.jboss.logging.Slf4jLoggerProvider found via system property
2016-12-07 16:43:18.499 DEBUG 6396 --- [ restartedMain] c.m.myapp.config.AsyncConfiguration : Creating Async Task Executor
2016-12-07 16:43:19.041 DEBUG 6396 --- [ restartedMain] c.m.myapp.config.MetricsConfiguration : Registering JVM gauges
2016-12-07 16:43:19.059 DEBUG 6396 --- [ restartedMain] c.m.myapp.config.MetricsConfiguration : Initializing Metrics JMX reporting
2016-12-07 16:43:19.960 WARN 6396 --- [ restartedMain] io.undertow.websockets.jsr : UT026009: XNIO worker was not set on WebSocketDeploymentInfo, the default worker will be used
2016-12-07 16:43:19.961 WARN 6396 --- [ restartedMain] io.undertow.websockets.jsr : UT026010: Buffer pool was not set on WebSocketDeploymentInfo, the default pool will be used
2016-12-07 16:43:20.436 INFO 6396 --- [ restartedMain] c.mycompany.myapp.config.WebConfigurer : Web application configuration, using profiles: [swagger, dev]
2016-12-07 16:43:20.437 DEBUG 6396 --- [ restartedMain] c.mycompany.myapp.config.WebConfigurer : Initializing Metrics registries
2016-12-07 16:43:20.442 DEBUG 6396 --- [ restartedMain] c.mycompany.myapp.config.WebConfigurer : Registering Metrics Filter
2016-12-07 16:43:20.442 DEBUG 6396 --- [ restartedMain] c.mycompany.myapp.config.WebConfigurer : Registering Metrics Servlet
2016-12-07 16:43:20.445 INFO 6396 --- [ restartedMain] c.mycompany.myapp.config.WebConfigurer : Web application fully configured
2016-12-07 16:43:20.491 INFO 6396 --- [ restartedMain] com.mycompany.myapp.MdcApp : Running with Spring profile(s) : [swagger, dev]
2016-12-07 16:43:20.579 DEBUG 6396 --- [ restartedMain] c.m.myapp.config.CacheConfiguration : No cache
2016-12-07 16:43:24.805 DEBUG 6396 --- [ restartedMain] c.m.m.c.apidoc.SwaggerConfiguration : Starting Swagger
2016-12-07 16:43:24.816 DEBUG 6396 --- [ restartedMain] c.m.m.c.apidoc.SwaggerConfiguration : Started Swagger in 10 ms
2016-12-07 16:43:24.849 DEBUG 6396 --- [ restartedMain] c.m.myapp.config.DatabaseConfiguration : Configuring Mongobee
2016-12-07 16:43:24.854 INFO 6396 --- [ restartedMain] com.github.mongobee.Mongobee : Mongobee has started the data migration sequence..
2016-12-07 16:43:54.876 WARN 6396 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongobee' defined in class path resource [com/mycompany/myapp/config/DatabaseConfiguration.class]: Invocation of init method failed; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
2016-12-07 16:43:54.883 INFO 6396 --- [ restartedMain] c.m.myapp.config.CacheConfiguration : Closing Cache Manager
2016-12-07 16:43:54.905 ERROR 6396 --- [ restartedMain] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongobee' defined in class path resource [com/mycompany/myapp/config/DatabaseConfiguration.class]: Invocation of init method failed; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at com.mycompany.myapp.MdcApp.main(MdcApp.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:369)
at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71)
at com.mongodb.binding.ClusterBinding.getReadConnectionSource(ClusterBinding.java:63)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:210)
at com.mongodb.operation.FindOperation.execute(FindOperation.java:482)
at com.mongodb.operation.FindOperation.execute(FindOperation.java:79)
at com.mongodb.Mongo.execute(Mongo.java:772)
at com.mongodb.Mongo$2.execute(Mongo.java:759)
at com.mongodb.DBCollection.findOne(DBCollection.java:777)
at com.mongodb.DBCollection.findOne(DBCollection.java:747)
at com.mongodb.DBCollection.findOne(DBCollection.java:694)
at com.github.mongobee.dao.ChangeEntryIndexDao.findRequiredChangeAndAuthorIndex(ChangeEntryIndexDao.java:26)
at com.github.mongobee.dao.ChangeEntryDao.ensureChangeLogCollectionIndex(ChangeEntryDao.java:75)
at com.github.mongobee.dao.ChangeEntryDao.connectMongoDb(ChangeEntryDao.java:34)
at com.github.mongobee.Mongobee.execute(Mongobee.java:135)
at com.github.mongobee.Mongobee.afterPropertiesSet(Mongobee.java:117)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)
... 19 common frames omitted
I tried to create a similar project but without a Mongodb and it worked.
This error means that there was an error connecting to your database, it confirms this in your stacktrace:
Timed out after 30000 ms while waiting for a server
Please double check your database configuration in the application-dev.properties or application-dev.yml file under src/main/resources/config/.
Depending on whether you use YAML or JSON as the property definition file, double check the database configuration:
YAML:
spring:
data:
mongodb:
host: <your_host_address>
port: <your_port>
database: <database_name>
JSON:
spring.data.mongodb.host=<your_host_address>
spring.data.mongodb.port=<your_port>
spring.data.mongodb.database=<database_name>
After creating a new JHipster project with MongoDb I had the same error.
Before running mvnw (on Windows) I forgot to run the MongoDb itself.
So running mongod.exe in the new command prompt, and then running mvnw solved the issue for me.
This was able to solve my problem:
"Answered my own question...removing the #Bean definition from public
Mongobee mongobee(...) in DatabaseConfiguration.java seems to do the
trick. Haven't done any thorough testing, but the apps starts and I
can create new users."
Link: https://github.com/jhipster/generator-jhipster/issues/8665