The log file exists and logs are generated but it isn't logging Processing index request in the logs.
Is the code correct? When index page is accessed the thymleaf content "DevOps" is being retrieved and displayed in index.html but no logs from logger.info in the logs.
package com.example.devops.web;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class WelcomeController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
#RequestMapping("/")
public String welcome(Model model) {
logger.info("Processing index request");
model.addAttribute("course", "DevOps");
return "index";
}
}
Log entires:
021-08-27 18:41:08.557 [INFO ] [localhost-startStop-1] c.e.d.ServletInitializer - Starting ServletInitializer v1.3.1-SNAPSHOT using Java 1.8.0_301 on DESKTOP-6O551TV with PID 23756 (F:\Devops\apache-tomcat-8.5.70\webapps\devops\WEB-INF\classes started by user in F:\Devops\apache-tomcat-8.5.70\bin)
2021-08-27 18:41:08.615 [INFO ] [localhost-startStop-1] c.e.d.ServletInitializer - The following profiles are active: dev
2021-08-27 18:41:09.573 [INFO ] [localhost-startStop-1] o.s.b.w.s.c.ServletWebServerApplicationContext - Root WebApplicationContext: initialization completed in 847 ms
2021-08-27 18:41:10.215 [INFO ] [localhost-startStop-1] o.s.b.a.w.s.WelcomePageHandlerMapping - Adding welcome page template: index
2021-08-27 18:41:10.374 [INFO ] [localhost-startStop-1] c.e.d.ServletInitializer - Started ServletInitializer in 2.416 seconds (JVM running for 11.278)
Actually its working as expected. application-dev.properties file did not have full path of the log and a couple of commits were missing.
It is working.
While starting the Spring boot, application gets stuck and SpringApplication.run is not returning.
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class AccountServiceApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(AccountServiceApplication.class, args);
System.out.println("----------------------------- I'm done -------------------------");
}
}
I can see that Spring creates all the beans but it never returns, though embedded tomcat is started on 9000, it's not listening
class org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory's object [after] tomcatEmbeddedServletContainerFactory
[05/16/19 06:17:44:044 IST] INFO tomcat.TomcatEmbeddedServletContainer: : Tomcat initialized with port(s): 9000 (http)
May 16, 2019 6:17:44 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-9000"]
May 16, 2019 6:17:44 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Tomcat]
Trying 127.0.0.1...
Connection failed: Connection refused
Trying ::1...
telnet: Unable to connect to remote host: Connection refused
Application is stuck forever post creating JMS connection.
class org.springframework.expression.spel.support.StandardEvaluationContext's object [after] integrationEvaluationContext
class org.springframework.integration.handler.LoggingHandler's object [after] _org.springframework.integration.errorLogger.handler
class org.springframework.integration.config.ConsumerEndpointFactoryBean's object [before]_org.springframework.integration.errorLogger
class org.springframework.integration.config.ConsumerEndpointFactoryBean's object [after] _org.springframework.integration.errorLogger
class org.springframework.integration.config.IdGeneratorConfigurer's object [before]org.springframework.integration.config.IdGeneratorConfigurer#0
class org.springframework.integration.config.IdGeneratorConfigurer's object [after] org.springframework.integration.config.IdGeneratorConfigurer#0
[05/16/19 05:58:02:002 IST] INFO annotation.AnnotationMBeanExporter: : Registering beans for JMX exposure on startup
class org.springframework.expression.spel.support.StandardEvaluationContext's object [after] integrationEvaluationContext
[05/16/19 05:58:02:002 IST] INFO support.DefaultLifecycleProcessor: : Starting beans in phase 0
[05/16/19 05:58:02:002 IST] INFO endpoint.EventDrivenConsumer: : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
[05/16/19 05:58:02:002 IST] INFO channel.PublishSubscribeChannel: : Channel 'application:9000.errorChannel' has 1 subscriber(s).
[05/16/19 05:58:02:002 IST] INFO endpoint.EventDrivenConsumer: : started _org.springframework.integration.errorLogger
[05/16/19 05:58:02:002 IST] INFO support.DefaultLifecycleProcessor: : Starting beans in phase 2147483647
[05/16/19 05:58:02:002 IST] INFO connection.CachingConnectionFactory: : Established shared JMS Connection: ActiveMQConnection {id=ID:SDSD121SFSSDF.local-54305-1557966482134-1:1,clientId=null,started=false}
Any pointer on how can I debug it?
in your application,it may be exist a thread with an infinite loop. your application start up fail. and this thread is not quit. the process still is exist.it looks like start up successfully.
The common practice that might help in such cases is to "catch the lion in the desert / binary search" for the cause the problem.
Try comment out halves of your application till you reach a point where the application starts with no problem. Then you will be able to nail the problematic code/section.
I also got stuck at :
INFO support.DefaultLifecycleProcessor: : Starting beans in phase X
It was because in a #RestController class I made a #GetMapping method return a #Entity, where it should have been a DTO instead.
I just wrote a Springboot application as a testing Webserver which origins from spring.io.
It packaged initially in "jar", changed it to "war" file.
And get the application class code as below:
package com.ronzhong;
import org.springframework.boot.Banner.Mode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.web.context.WebApplicationContext;
#SpringBootApplication(scanBasePackages={"com.ronzhong.libraryManagement"})
public class LibraryManagementApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
application.application().setBannerMode(Mode.OFF);
return application.sources(SpringApplicationBuilder.class);
}
protected WebApplicationContext run(SpringApplication application) {
return (WebApplicationContext) application.run();
}
// public static void main(String[] args) {
// SpringApplication.run(LibraryManagementApplication.class, args);
//}
}
and the controller is :
package com.ronzhong.libraryManagement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.*;
//#CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
#RestController
#RequestMapping("/api")
public class CounterController {
#Autowired
private BookService bookService;
#PostMapping
public boolean add(#RequestBody Book book){
return bookService.add(book);
}
#RequestMapping(value = "/books", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Book[] get(){
return bookService.getBooks();
}
#RequestMapping(value = "{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Book findOne(#PathVariable("id") int id){
return bookService.findById(id);
}
}
And I also checked the
"Dynamic Web Module" in the project facets.
Finally, I got these logs when launch tomcat server with this war file generated.
INFO: 2 Spring WebApplicationInitializers detected on classpath
2018-11-28 10:43:31.925 INFO 14888 --- [ main] c.ronzhong.LibraryManagementApplication : Starting LibraryManagementApplication on ronzhongmachine with PID 14888 (C:\Users\ronzhong\workspace_testserver\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\library-Management\WEB-INF\classes started by ronzhong in C:\tools_installers\eclipse-jee-2018-09-win32-x86_64\eclipse)
2018-11-28 10:43:32.002 INFO 14888 --- [ main] c.ronzhong.LibraryManagementApplication : No active profile set, falling back to default profiles: default
2018-11-28 10:43:33.910 INFO 14888 --- [ main] o.a.c.c.C.[.[.[/library-Management] : Initializing Spring embedded WebApplicationContext
2018-11-28 10:43:33.911 INFO 14888 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1604 ms
2018-11-28 10:43:34.362 INFO 14888 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'errorPageFilter' to: [/*]
2018-11-28 10:43:34.704 INFO 14888 --- [ main] c.ronzhong.LibraryManagementApplication : Started LibraryManagementApplication in 5.958 seconds (JVM running for 36.407)
2018-11-28 10:43:34.955 INFO 14888 --- [ main] org.apache.coyote.ajp.AjpNioProtocol : Starting ProtocolHandler ["ajp-nio-8009"]
2018-11-28 10:43:34.968 INFO 14888 --- [ main] org.apache.catalina.startup.Catalina : Server startup in 28177 ms
There're no mappings info in the logs.
And if I request with http://localhost:8080/api/books, it will get 404 error.
But the logs hasn't change even a little.
So I googled the potential causes, and excluded those causes temporarily:
springboot application does not scan the package which controller locates?
I moved springboot application class to the uplevel package, and also specified what kind of package it should scan.
While you see, it doesn't work.
the annotation issue?
Some people say we should use #RestController annotation instead of #Controller, better add the #ResponseBody, while I did.
it does't work, either.
the deployment issue?
don't know, I did changed the build path of this project, which generated jar file and war file normally, but webapp folder is empty, since I don't have any static resource, I think it's fine, right?
Anyone can help me? very appreciate for your answer, thanks in advance.
From the logs, I can see that your war file name is library-Management, whichh means its deloyed under this folder, as logs states. So you should check http://localhost:8080/library-Management/api/books instead.
You get 404 from Tomcat, it doesnt hit your app at all, this is ehy you dont see any logs.
I am learning spring-cloud-config and I would like to use different profiles but I always get back values from the default profile.
I have two property files in the git repository and the file with prod suffix overrides a key from default profile:
image-service.properties
image-service-prod.properties
It seems that my config server works fine:
GET http://localhost:8888/image-service/default:
{"name":"image-service","profiles":["default"],"label":null,"version":"fb78fe4429a33c266d6eb07a9e482b8fd264dd7c","state":null,"propertySources":
[{"name":"https://bitbucket.org/.../...-configuration.git/image-service.properties","source":{"service.image.hello":"image-common"}}]}
GET http://localhost:8888/image-service/prod
{"name":"image-service","profiles":["prod"],"label":null,"version":"fb78fe4429a33c266d6eb07a9e482b8fd264dd7c","state":null,"propertySources":
[{"name":"https://bitbucket.org/.../...-configuration.git/image-service-prod.properties","source":{"service.image.hello":"image-prod"}},
{"name":"https://bitbucket.org/.../...-configuration.git/image-service.properties","source":{"service.image.hello":"image-common"}}]}
I activated prod profile in my REST application but always value from the default profile is shown.
application.properties of the client app:
server.port=8889
spring.application.name=image-service
spring.cloud.config.uri=http://localhost:8888
spring.profiles.active=prod
REST controller of the client app:
#RefreshScope
#RestController
public class EchoController {
#Value("${service.image.hello}")
private String hello;
#RequestMapping("/show")
#ResponseBody
public String showConfig() {
return new StringBuilder()
.append("image-service: ").append(hello)
.toString();
}
}
Result:
image-service: image-common
Log from client app:
c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
c.c.c.ConfigServicePropertySourceLocator : Located environment: name=image-service, profiles=[default], label=null, version=fb78fe4429a33c266d6eb07a9e482b8fd264dd7c, state=null
b.c.PropertySourceBootstrapConfiguration : Located property source: CompositePropertySource {name='configService', propertySources=[MapPropertySource {name='configClient'}, MapPropertySource {name='https://bitbucket.org/.../...-configuration.git/image-service.properties'}]}
c.r.d.springconfig.client.Application : The following profiles are active: prod
ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#7ccdc9e7: startup date [Sun Sep 23 22:31:55 CEST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext#7fd618b5
o.s.cloud.context.scope.GenericScope : BeanFactory id=51790958-c0a2-3d61-91d6-a8dcd5395c7e
trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$bf37cae6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8889 (http)
It seems I missed something but I can not see what.
This question is already asked and i have checked all the solutions, but nothing helped me, am still facing the same issue.
I have configured My Google Appengine Project To Use Spring MVC Using Java Config, and i set the logging level for spring as INFO to check the initialization log.
This is what am getting upon initialization,
14:52:37,885 INFO [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'SpringMvcConfig': initialization started
14:52:37,885 INFO [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'SpringMvcConfig': initialization started
14:52:37,927 INFO [org.springframework.web.context.support.AnnotationConfigWebApplicationContext] - Refreshing WebApplicationContext for namespace 'SpringMvcConfig-servlet': startup date [Sun Sep 08 14:52:37 UTC 2013]; root of context hierarchy
14:52:37,927 INFO [org.springframework.web.context.support.AnnotationConfigWebApplicationContext] - Refreshing WebApplicationContext for namespace 'SpringMvcConfig-servlet': startup date [Sun Sep 08 14:52:37 UTC 2013]; root of context hierarchy
14:52:38,087 INFO [org.springframework.context.annotation.ClassPathBeanDefinitionScanner] - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
14:52:38,087 INFO [org.springframework.context.annotation.ClassPathBeanDefinitionScanner] - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
14:52:38,093 INFO [org.springframework.web.context.support.AnnotationConfigWebApplicationContext] - Successfully resolved class for [com.test.config.SpringMvcConfig]
14:52:38,093 INFO [org.springframework.web.context.support.AnnotationConfigWebApplicationContext] - Successfully resolved class for [com.test.config.SpringMvcConfig]
14:52:38,239 INFO [org.springframework.context.annotation.ClassPathBeanDefinitionScanner] - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
14:52:38,239 INFO [org.springframework.context.annotation.ClassPathBeanDefinitionScanner] - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
14:52:38,826 INFO [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
14:52:38,826 INFO [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
14:52:38,987 INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#7fa6e654: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,springMvcConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,mainController,org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration,requestMappingHandlerMapping,mvcContentNegotiationManager,mvcConversionService,viewControllerHandlerMapping,beanNameHandlerMapping,resourceHandlerMapping,defaultServletHandlerMapping,requestMappingHandlerAdapter,mvcValidator,httpRequestHandler Adapter,simpleControllerHandlerAdapter,handlerExceptionResolver,getInternalResourceViewResolver]; root of factory hierarchy
14:52:38,987 INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#7fa6e654: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,springMvcConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,mainController,org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration,requestMappingHandlerMapping,mvcContentNegotiationManager,mvcConversionService,viewControllerHandlerMapping,beanNameHandlerMapping,resourceHandlerMapping,defaultServletHandlerMapping,requestMappingHandlerAdapter,mvcValidator,httpRequestHandlerAdapter,simpleControllerHandlerAdapter,handlerExceptionResolver,getInternalResourceViewResolver]; root of factory hierarchy
14:52:39,378 INFO [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Mapped "{[/ || /login],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto java.lang.String com.test.controller.MainController.hanldeRequest()
14:52:39,378 INFO [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Mapped "{[/ || /login],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto java.lang.String com.test.controller.MainController.hanldeRequest()
14:52:39,449 INFO [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping] - Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler]
14:52:39,449 INFO [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping] - Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler]
14:52:40,355 INFO [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'SpringMvcConfig': initialization completed in 2468 ms
14:52:40,355 INFO [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'SpringMvcConfig': initialization completed in 2468 ms
spring mvc is initialized twice, following is my configuration
web.xml
<servlet>
<servlet-name>SpringMvcConfig</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.test.config.SpringMvcConfig
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMvcConfig</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and My Spring MVC Configuration looks like this,
#Configuration
#EnableWebMvc
#ComponentScan("com.test.controller")
public class SpringMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false).favorParameter(true).ignoreAcceptHeader(true)
.useJaf(false).defaultContentType(MediaType.APPLICATION_JSON).mediaType("json", MediaType.APPLICATION_JSON);
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(new CustomJacksonObjectMapper());
converters.add(converter);
}
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setCache(false);
return resolver;
}
}
Can anyone help me fix this?
Any Solution or suggestion would be very helpful.
Thanks!
If we look at your log4j.properties file
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%c] - %m%n
log4j.logger.org.apache = WARN, A1
log4j.logger.org.springframework = INFO, A1
Both the logger for org.springframework and the root logger are configured to use the A1 appender. If you don't set the additivity flag to false, they will both append.
Appender Additivity
The output of a log statement of logger C will go
to all the appenders in C and its ancestors. This is the meaning of
the term "appender additivity".
However, if an ancestor of logger C, say P, has the additivity flag set to false, then C's output will be directed to all the appenders in C and its ancestors upto and including P but not the appenders in any of the ancestors of P.
Loggers have their additivity flag set to true by default.
log4j.additivity.org.springframework=false
Either do that or remove the A1 appender from the rootLogger
log4j.rootLogger=DEBUG
i had a very similar problem in tomcat because the context was being loaded twice. once by a context load listener (to configure a servlet filter) and once by the dispatch servlet. so i wonder if you are doing something similar?
in other words, some things in spring load contexts by default. try disabling the explicit loading of context and see what happens.
in my case, the solution was to separate the contexts - have different contexts for the filter and servlet. then each was loaded correctly without overlap.
edit: hmm, expanding comments i see you've found a similar answer. i'd encourage you to follow that up more closely. you really need to work out what is loading the extra context. look for context files with "special" names (eg named after a servlet or similar). then try changing their names, for example. in short - you need to find / break the auto-load.