I have simple spring boot app with web socket configuration.
When i run my app with SimpleBroker(provided by spring) everything works fine, but when i want to use rabbitmq instead of SimpleBroker, i have some problems, my broker is "not available"
#Configuration
#EnableWebSocketMessageBroker
open class WebSocketConfig : ILogging by LoggingImp<WebSocketConfig>(),
WebSocketMessageBrokerConfigurer {
#Autowired
private lateinit var env: Environment
override fun registerStompEndpoints(registry: StompEndpointRegistry) {
registry.addEndpoint("/hig").setAllowedOrigins("*").withSockJS()
}
override fun configureMessageBroker(registry: MessageBrokerRegistry) {
registry.setApplicationDestinationPrefixes("/app")
val host = env.getProperty("spring.rabbitmq.host")!!
val port = env.getProperty("spring.rabbitmq.port")!!.toInt()
val login = env.getProperty("spring.rabbitmq.username")!!
val pass = env.getProperty("spring.rabbitmq.password")!!
log.debug("webSocket=$host, $port, $login, $pass")
// registry.enableSimpleBroker("/chat")
registry.enableStompBrokerRelay("/chat")
.setRelayHost(host)
.setRelayPort(port)
.setClientLogin(login)
.setClientPasscode(pass)
.setAutoStartup(true)
.setSystemHeartbeatReceiveInterval(10000)
.setSystemHeartbeatSendInterval(10000)
}
}
response from WebSocketMessageBrokerStats:
{
"loggingPeriod": 1800000,
"webSocketSessionStatsInfo": "0 current WS(0)-HttpStream(0)-HttpPoll(0), 0 total, 0 closed abnormally (0 connect failure, 0 send limit, 0 transport error)",
"stompSubProtocolStatsInfo": "processed CONNECT(0)-CONNECTED(0)-DISCONNECT(0)",
"stompBrokerRelayStatsInfo": "1 sessions, localhost:5672 (not available), processed CONNECT(1)-CONNECTED(0)-DISCONNECT(0)",
"clientInboundExecutorStatsInfo": "pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0",
"clientOutboundExecutorStatsInfo": "pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0",
"sockJsTaskSchedulerStatsInfo": "pool size = 1, active threads = 0, queued tasks = 1, completed tasks = 0"
}
Broker details:
2018-02-15 23:03:56.367 [XNIO-2 task-16] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/hig/websocket]
2018-02-15 23:03:56.367 [XNIO-2 task-16] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /hig/websocket
2018-02-15 23:03:56.368 [XNIO-2 task-16] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Did not find handler method for [/hig/websocket]
2018-02-15 23:03:56.368 [XNIO-2 task-16] DEBUG o.s.w.s.s.s.WebSocketHandlerMapping - Matching patterns for request [/hig/websocket] are [/hig/**]
2018-02-15 23:03:56.368 [XNIO-2 task-16] DEBUG o.s.w.s.s.s.WebSocketHandlerMapping - URI Template variables for request [/hig/websocket] are {}
2018-02-15 23:03:56.368 [XNIO-2 task-16] DEBUG o.s.w.s.s.s.WebSocketHandlerMapping - Mapping [/hig/websocket] to HandlerExecutionChain with handler [org.springframework.web.socket.sockjs.support.SockJsHttpRequestHandler#352c1b98] and 1 interceptor
2018-02-15 23:03:56.368 [XNIO-2 task-16] DEBUG o.s.web.servlet.DispatcherServlet - Last-Modified value for [/hig/websocket] is: -1
2018-02-15 23:03:56.369 [XNIO-2 task-16] DEBUG o.s.w.s.s.t.h.DefaultSockJsService - Processing transport request: GET http://localhost:8080/hig/websocket
2018-02-15 23:03:56.370 [XNIO-2 task-16] DEBUG o.s.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2018-02-15 23:03:56.370 [XNIO-2 task-16] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request
2018-02-15 23:03:56.371 [XNIO-2 task-16] DEBUG o.s.w.s.h.LoggingWebSocketHandlerDecorator - New StandardWebSocketSession[id=Enl3glxP29UhO95gUafWViRXrXaZn3Kv556EVxW4, uri=/hig/websocket]
2018-02-15 23:03:56.374 [clientOutboundChannel-7] DEBUG o.s.w.s.a.NativeWebSocketSession - Closing StandardWebSocketSession[id=Enl3glxP29UhO95gUafWViRXrXaZn3Kv556EVxW4, uri=/hig/websocket]
2018-02-15 23:03:56.374 [clientOutboundChannel-7] DEBUG o.s.w.s.h.LoggingWebSocketHandlerDecorator - StandardWebSocketSession[id=Enl3glxP29UhO95gUafWViRXrXaZn3Kv556EVxW4, uri=/hig/websocket] closed with CloseStatus[code=1002, reason=]
2018-02-15 23:03:56.374 [clientOutboundChannel-7] DEBUG o.s.w.s.m.SubProtocolWebSocketHandler - Clearing session Enl3glxP29UhO95gUafWViRXrXaZn3Kv556EVxW4
2018-02-15 23:03:56.375 [clientOutboundChannel-8] DEBUG o.s.w.s.m.SubProtocolWebSocketHandler - No session for GenericMessage [payload=byte[0], headers={simpMessageType=OTHER, stompCommand=ERROR, nativeHeaders={message=[Broker not available.]}, simpSessionId=Enl3glxP29UhO95gUafWViRXrXaZn3Kv556EVxW4}]
For client i'm using angular 5
When i'm using registry.enableSimpleBroker("/chat") everything works fine
When i enable registry.enableStompBrokerRelay("/chat")... i'm getting:
message:Broker not available.
content-length:0
pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.0.0.M7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
<version>2.0.0.M7</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-net</artifactId>
<version>2.0.8.RELEASE</version>
</dependency>
<dependency>
<groupId>io.projectreactor.ipc</groupId>
<artifactId>reactor-netty</artifactId>
<version>0.7.3.RELEASE</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.21.Final</version>
</dependency>
You are trying to connect using stomp protocol on a rabbitmq which doesn't run the stomp adapter.
Run:
rabbitmq-plugins enable rabbitmq_stomp
to enable stomp.
Also, you are connecting to the port 5672 which is the amqp protocol / adapter. This is why you have this stompCommand=ERROR, nativeHeaders={message=[Broker not available.]}.
Once enabled, the stomp adapter will by default listen on tcp/61613.
Related
I am trying to use Spring cloud Sleuth, however i am facing an issue with having proper log information. My application does not propagate traceId and spanId for RestTemplate.
I am using the latest version of Sleuth.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
<version>3.0.3</version>
</dependency>
This is the logs:
2021-07-19 10:46:22.834 DEBUG [My app,340b0c68ce92b6be,340b0c68ce92b6be] 28840 --- [ Thread-3] org.apache.http.headers : http-outgoing-0 << Date: Mon, 19 Jul 2021 08:46:15 GMT
2021-07-19 10:46:22.834 DEBUG [My app,340b0c68ce92b6be,340b0c68ce92b6be] 28840 --- [ Thread-3] o.a.http.impl.execchain.MainClientExec : Connection can be kept alive indefinitely
2021-07-19 10:46:22.834 DEBUG [My app,,] 28840 --- [ Thread-3] o.s.web.client.RestTemplate : Response 200 OK
2021-07-19 10:46:22.834 DEBUG [My app,,] 28840 --- [ Thread-3] o.s.web.client.RestTemplate : Reading to [com.app.myapp.DeviceService]
2021-07-19 10:46:22.834 DEBUG [My app,,] 28840 --- [ Thread-3] h.i.c.PoolingHttpClientConnectionManager : Connection [id: 0][route: {s}->https://ttsce.dot.eu:443] can be kept alive indefinitely
2021-07-19 10:46:22.844 DEBUG [My app,,] 28840 --- [ Thread-3] .w.m.TracingClientHttpRequestInterceptor : Wrapping an outbound http call with span [NoopSpan(4bda0829902d27f6/4bda0829902d27f6)]
2021-07-19 10:46:22.844 DEBUG [My app,4bda0829902d27f6,4bda0829902d27f6] 28840 --- [ Thread-3] o.a.h.client.protocol.RequestAddCookies : CookieSpec selected: default
This is how i am craeting my RestTemplate bean (i was testing with both those setups of the bean).
#Primary
#Bean("newRestTemplate")
public RestTemplate restTemplate() {
return new RestTemplate();
}
#Bean("customRestTemplate")
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.setConnectTimeout(Duration.ofMillis(300000))
.setReadTimeout(Duration.ofMillis(300000)).build();
}
I have a spring cloud services with the following spring package versions
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.4.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server</artifactId>
<version>1.3.7</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui</artifactId>
<version>1.3.7</version>
</dependency>
and I have my spring boot admin server ui running in 9003 port. I am using eureka discovery client to register my end points to the registry service.
My application.yml for the service is contains the following configurations.
server:
context-path: /myservice
port: 0
management:
context-path: /mng
security:
enabled: false
eureka:
instance:
preferIpAddress: true
statusPageUrlPath: ${server.context-path:}${management.context-path:}/info
healthCheckUrlPath: ${server.context-path:}${management.context-path:}/health
client:
serviceUrl:
defaultZone: http://${EUREKA_DNS:localhost}:8761/eureka/
When I start my service I can see the following logs regarding my api endpoint
2018-01-11 16:01:22.176 INFO 6070 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/mng/health || /mng/health.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.HealthMvcEndpoint.invoke(java.security.Principal)
2018-01-11 16:01:22.177 INFO 6070 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/mng/info || /mng/info.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-01-11 16:01:22.177 INFO 6070 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/mng/mappings || /mng/mappings.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-01-11 16:01:22.177 INFO 6070 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/mng/metrics/{name:.*}],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)
2018-01-11 16:01:22.178 INFO 6070 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/mng/metrics || /mng/metrics.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
when I start my dashboard following mapping info logs are printed
2018-01-11 22:04:00.886 INFO 55 --- [tp1976870338-18] o.s.c.n.zuul.web.ZuulHandlerMapping : Mapped URL path [/api/applications/c5a746b1/health/**] onto handler of type [class org.springframework.cloud.netflix.zuul.web.ZuulController]
2018-01-11 22:04:00.886 INFO 55 --- [tp1976870338-18] o.s.c.n.zuul.web.ZuulHandlerMapping : Mapped URL path [/api/applications/c5a746b1/env/**] onto handler of type [class org.springframework.cloud.netflix.zuul.web.ZuulController]
2018-01-11 22:04:00.886 INFO 55 --- [tp1976870338-18] o.s.c.n.zuul.web.ZuulHandlerMapping : Mapped URL path [/api/applications/c5a746b1/metrics/**] onto handler of type [class org.springframework.cloud.netflix.zuul.web.ZuulController]
My problem now is when I open my dashboard Ui, its is trying to get the metrics info from "/api/applications/c5a746b1/metrics" but it returns 404 error. but in the browser when I type manually "/myservice/mng/metrics", I can see the metrics info.
I am newbee to the spring cloud , any help appreciated.
thanks in advance
You should update to a 1.4.x and add a mangament.context-path entry to the services' metadata. This way the SBA server knows the correct path of your actuator endpoints.
I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
this is the main class
#SpringBootApplication
public class TdkApplication {
public static void main(String[] args) {
SpringApplication.run(TdkApplication.class, args);
}
}
This is a controller
#Controller
public class MockupIndexController {
#RequestMapping("/mockup/index")
public String welcome(Map<String, Object> model) {
return "mockups/index";
}
}
This my pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.tdk.iot.core</groupId>
<artifactId>tdk-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
But when I put this in the URL:
http://localhost:8080/mockup/index
I got the following log in the console
o.s.web.servlet.DispatcherServlet : Servlet 'dispatcherServlet' configured successfully
o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/mockup/index]
s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /mockup/index
s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/mockup/index]
o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/mockup/index] are [/**]
o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/mockup/index] are {}
o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/mockup/index] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#8b91134]]] and 1 interceptor
o.s.web.servlet.DispatcherServlet : Last-Modified value for [/mockup/index] is: -1
o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
o.s.web.servlet.DispatcherServlet : Successfully completed request
o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
I assume your controller class is not found during scanning cause it is in a package that will not be scanned by default. I guess your application is in something like com.tdk.app and your controller in com.tdk.controller, right? If yes just move the app one level up to com.tdk and your issue should go away.
The controller package should be the one level bottom package of "TdkApplication" if your "TdkApplication" is in com.test package, Then your controller should be under com.test.controller package. Means one level down package when we comparing with application package
following will work
App package should be like com.app
then controller would be com.app.controller.
if you use it like below then spring would be unable to scan the controller
App package: com.app.main
controller:com.app.controller
Any takers to resolve this issue for USD50, please contact
I am getting the not acceptable according to the request "accept" headers, however, I believe I have done everything right, I could. Can someone help to resolve this issue. I am using Spring 4.1.
The OBJECTIVE is to be able to return the response in the text/xml format. if I remove produces=text/xml directive then my application works i.e. no error, but the source system treat the response in an unexpected way.
Request coming in as follows:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic YWRtaW46YWRtaW4=" -H "Cache-Control: no-cache" -H "Postman-Token: 78637a4f-e153-4242-c922-96757d01442a" -d Then values....
My Pom:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.0.rc1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.0.rc1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
My Controller have the following notations:
#RestController
#RequestMapping("/test")
#EnableWebMvcMy Controller has the following notations:
Main Class has the following notation
#Configuration
#EnableAutoConfiguration
#ComponentScan
I DO NOT have the application context xml, as i am using #Autowired
on my end-point method as follows
#RequestMapping(value="/IDEA", headers = {"Accept=*/*"}, produces="text/xml", method= {RequestMethod.POST, RequestMethod.GET})
#Autowired
public MyResult processMyRequest(HttpServletRequest request)
Current Log
2016-08-11 13:38:04.076 INFO 89535 --- [nio-8080-exec-2] c.f.fnocc.injestor.MyController : POST CALLED
2016-08-11 13:38:04.079 INFO 89535 --- [nio-8080-exec-2] c.f.fnocc.injestor.MyController : Request received from ipAddress:0:0:0:0:0:0:0:1
2016-08-11 13:38:04.082 INFO 89535 --- [nio-8080-exec-2] c.f.fnocc.injestor.MyController : REQUEST INFORMATION: [
2016-08-11 13:38:04.084 INFO 89535 --- [nio-8080-exec-2] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#af3b571: startup date [Thu Aug 11 13:38:04 BST 2016]; root of context hierarchy
2016-08-11 13:38:04.095 INFO 89535 --- [nio-8080-exec-2] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-08-11 13:38:04.119 INFO 89535 --- [nio-8080-exec-2] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#142abfa2: startup date [Thu Aug 11 13:38:04 BST 2016]; root of context hierarchy
2016-08-11 13:38:04.124 INFO 89535 --- [nio-8080-exec-2] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-08-11 13:38:04.150 ERROR 89535 --- [nio-8080-exec-2] c.f.fnocc.injestor.MyController : Error has occurred.
The first issue I see is #EnableWebMvc should be specified on the main class alongside the #Configuration but I don't think it is even needed when you are specifying #EnableAutoConfiguration.
The other issue is the #RequestMapping() has an attribute for consumes which is what you should probably be using instead of looking for the accept header. Reason for that is the accept header normally includes multiple media types not just */* as such the check for equality on that header wouldn't be there.
* Update * I was wrong on the consumes that is used to interpreting the Content-Type header and not the Accept header. Spring tries to match the produces to the Accept header to determine if the method can respond to the incoming request. That makes more sense why you are getting the 406 error as Spring sees the method trying to output text/xml but the request probably doesn't accept that content type in the Accept header.
To further troubleshoot you can setup a request logger to see the specifics on how the request is coming into the service to determine if there is something that is causing Spring to not process it properly. If you add the following bean and enable DEBUG level logging on org.springframework.web.filter.CommonsRequestLoggingFilterthen you can see.
#Bean
public Filter logFilter() {
CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
filter.setIncludeQueryString(false);
filter.setIncludePayload(false);
filter.setIncludeHeaders(true);
return filter;
}
If you can update your question with that request log that would help to troubleshoot.
* Update #2 * Was able to reproduce the error. Adding DEBUG logging level for org.springframework.web showed the issue more clearly.
2016-08-11 02:26:58.242 DEBUG 82904 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/test/IDEA]
2016-08-11 02:26:58.244 DEBUG 82904 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /test/IDEA
2016-08-11 02:26:58.247 DEBUG 82904 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public ca.tuatara.stackoverflow.MyController$MyResult ca.tuatara.stackoverflow.MyController.processMyRequest(javax.servlet.http.HttpServletRequest)]
2016-08-11 02:26:58.247 DEBUG 82904 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/test/IDEA] is: -1
2016-08-11 02:26:58.258 DEBUG 82904 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolving exception from handler [public ca.tuatara.stackoverflow.MyController$MyResult ca.tuatara.stackoverflow.MyController.processMyRequest(javax.servlet.http.HttpServletRequest)]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
The Could not find acceptable representation is the key. By specifying that you want XML you must include a library to marshall the object as XML as described on the Spring MVC docs. Adding the dependency for:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Made it work for my sample application. Give that a try!
I read in spring boot docs (https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html)
you can also specify debug=true in your application.properties"
So I guess I can turn off the debug logs by adding debug=false in application.properties. I did it but unfortunately, it didn't work. Then I read in the same doc
The logging system is initialized early in the application lifecycle and as such logging properties will not be found in property files loaded via #PropertySource annotations"
and
"Since logging is initialized before the ApplicationContext is created, it isn’t possible to control logging from #PropertySources in Spring #Configuration files"
and
"When possible we recommend that you use the -spring variants for your logging configuration" so I added a file named log4j-spring.properties in src/main/resources.
In such file, I added debug=false (only this line and nothing else) but I am still seeing all "current date" [main] DEBUG ... messages. So, my question is how can I turn off the debug messages in my Spring Boot Application as I will deploy to the application to production. Is there a recommended way to reach this via maven?
Added in Feb 12th
The two main methods:
1)By using AnnotationConfigApplicationContext:
public class DemoAppNoBoot {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
BatchConfiguration.class);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("job");
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Snippet output:
08:26:18.713 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
08:26:18.744 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
08:26:18.744 [main] DEBUG o.s.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
08:26:18.947 [main] INFO o.s.c.a.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#532760d8: startup date [Fri Feb 12 08:26:18 CST 2016]; root of context hierarchy
08:26:18.947 [main] DEBUG o.s.c.a.AnnotationConfigApplicationContext - Bean factory for org.springframework.context.annotation.AnnotationConfigApplicationContext#532760d8: org.springframework.beans.factory.support.DefaultListableBeanFactory#50b494a6: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,batchConfiguration]; root of factory hierarchy
08:26:18.979 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean
...
08:26:32.560 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
08:26:32.560 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalScheduledAnnotationProcessor'
08:26:32.560 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor'
08:26:32.560 [main] DEBUG o.s.s.a.ScheduledAnnotationBeanPostProcessor - Could not find default TaskScheduler bean
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.scheduling.TaskScheduler] is defined at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:372) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:332) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
...
08:26:33.529 [pool-1-thread-1] DEBUG o.s.jdbc.core.JdbcTemplate - Executing prepared SQL update
08:26:33.529 [pool-1-thread-1] DEBUG o.s.jdbc.core.JdbcTemplate - Executing prepared SQL statement [UPDATE BATCH_JOB_EXECUTION set START_TIME = ?, END_TIME = ?, STATUS = ?, EXIT_CODE = ?, EXIT_MESSAGE = ?, VERSION = ?, CREATE_TIME = ?, LAST_UPDATED = ? where JOB_EXECUTION_ID = ? and VERSION = ?]
08:26:33.529 [pool-1-thread-1] DEBUG o.s.jdbc.core.JdbcTemplate - SQL update affected 1 rows
08:26:33.545 [pool-1-thread-1] DEBUG o.s.j.d.DataSourceTransactionManager - Initiating transaction commit
08:26:33.545 [pool-1-thread-1] DEBUG o.s.j.d.DataSourceTransactionManager - Committing JDBC transaction on Connection [org.hsqldb.jdbc.JDBCConnection#33bbce9c]
08:26:33.545 [pool-1-thread-1] DEBUG o.s.j.d.DataSourceTransactionManager - Releasing JDBC Connection [org.hsqldb.jdbc.JDBCConnection#33bbce9c] after transaction
08:26:33.545 [pool-1-thread-1] DEBUG o.s.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
08:26:33.545 [pool-1-thread-1] INFO o.s.b.c.l.support.SimpleJobLauncher - Job: [SimpleJob: [name=job1]] completed with the following parameters: [{}] and the following status: [COMPLETED]
Main method with SpringApplication.run
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(BatchConfiguration.class, args);
}
}
Entire output:
: Spring Boot :: (v1.3.1.RELEASE)
2016-02-12 08:02:36.145 INFO 12172 --- [ main] com.example.DemoApplication : Starting DemoApplication on GH-VDIKCISV252 with PID 12172 (C:\STS\wsRestTemplate\demo\target\classes started by e049447 in C:\STS\wsRestTemplate\demo)
2016-02-12 08:02:36.145 INFO 12172 --- [ main] com.example.DemoApplication : No active profile set, falling back to default profiles: default
2016-02-12 08:02:36.473 INFO 12172 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#4e4aea35: startup date [Fri Feb 12 08:02:36 CST 2016]; root of context hierarchy
2016-02-12 08:02:42.176 WARN 12172 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method ScopeConfiguration.stepScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details.
2016-02-12 08:02:42.349 WARN 12172 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method ScopeConfiguration.jobScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details.
2016-02-12 08:02:42.724 INFO 12172 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Starting embedded database: url='jdbc:hsqldb:mem:testdb', username='sa'
2016-02-12 08:02:43.802 WARN 12172 --- [ main] o.s.b.c.l.AbstractListenerFactoryBean : org.springframework.batch.item.ItemReader is an interface. The implementing class will not be queried for annotation based listener configurations. If using #StepScope on a #Bean method, be sure to return the implementing class so listner annotations can be used.
2016-02-12 08:02:44.990 INFO 12172 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql]
2016-02-12 08:02:45.179 INFO 12172 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql] in 189 ms.
2016-02-12 08:02:46.804 INFO 12172 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-02-12 08:02:46.868 INFO 12172 --- [ main] o.s.b.a.b.JobLauncherCommandLineRunner : Running default command line with: []
2016-02-12 08:02:46.962 INFO 12172 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: HSQL
2016-02-12 08:02:47.040 INFO 12172 --- [pool-2-thread-1] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: HSQL
2016-02-12 08:02:47.243 INFO 12172 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2016-02-12 08:02:47.259 INFO 12172 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2016-02-12 08:02:47.321 INFO 12172 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] launched with the following parameters: [{run.id=1}]
2016-02-12 08:02:47.368 INFO 12172 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [step1]
2016-02-12 08:02:47.400 INFO 12172 --- [ main] com.example.CustomItemReader : read method - collecting the MYAPP2 out file names
2016-02-12 08:02:47.525 INFO 12172 --- [ main] com.example.CustomItemReader : read method - no file found
2016-02-12 08:02:47.556 INFO 12172 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] completed with the following parameters: [{run.id=1}] and the following status: [COMPLETED]
2016-02-12 08:02:47.556 INFO 12172 --- [ main] com.example.DemoApplication : Started DemoApplication in 12.1 seconds (JVM running for 13.405)
2016-02-12 08:02:47.556 INFO 12172 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] launched with the following parameters: [{}]
2016-02-12 08:02:47.618 INFO 12172 --- [pool-2-thread-1] o.s.batch.core.job.SimpleStepHandler : Executing step: [step1]
2016-02-12 08:02:47.634 INFO 12172 --- [pool-2-thread-1] com.example.CustomItemReader : read method - collecting the MYAPP2 out file names
2016-02-12 08:02:47.634 INFO 12172 --- [pool-2-thread-1] com.example.CustomItemReader : read method - no file found
2016-02-12 08:02:47.650 INFO 12172 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] completed with the following parameters: [{}] and the following status: [COMPLETED]
BatchConfiguration class
#Configuration
#ComponentScan("com.example")
#EnableBatchProcessing
#EnableAutoConfiguration
#EnableScheduling
#PropertySource("config.properties")
public class BatchConfiguration {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Bean
public Step step1(ItemReader<String> reader,
ItemProcessor<String, String> processor, ItemWriter<String> writer) {
return stepBuilderFactory.get("step1").<String, String> chunk(1) .reader(reader).processor(processor).writer(writer)
.allowStartIfComplete(true).build();
}
//I took out the rest of BatchConfiguration class
Application.properties (only one line)
logging.level.*=OFF
P.S. I will not show config.properties because it only contains several property names with path settup used in business logic
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<spring.batch.version>3.0.6.RELEASE</spring.batch.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.example.DemoAppNoBoot</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<goals>install</goals>
<preparationGoals>install</preparationGoals>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.example.DemoAppNoBoot</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
Maven Dependencies (the relevant ones for my doubt):
logback-classic-1.1.3.jar
logback-core-1.1.3.jar
slf4j-api-1.7.13.jar
log4j-over-slf4j-1.7.13.jar
In application.properties you can add ‘logging.level.*=LEVEL’ where ‘LEVEL’ is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF. * is responsible for package/class.
For example
logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
This means that root logger has WARN level.
org.springframework.web is on DEBUG level, but all hibernates files are logged only ERROR.
In your case you must set logging.level.root on one of level from INFO, WARN, ERROR,FATAL or OFF to turn off all logging.
See https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html#boot-features-custom-log-levels
While using Spring Rest Docs with SpringMockMVC with testLogging.showStandardStreams set to true in Gradle, Spring cluttered the console with info & debug logs. I had to use Mkyong's solution where in a logback-test.xml in src/test/resources needs to be created on top of the chosen solution here. Use log-level OFF, ERROR, WARN, DEBUG
logback-test.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<logger name="org.springframework" level="ERROR"/>
</configuration>
in addition to a log4j.properties or log4j.xml file you will need all three of these entries in your maven pom.xml... adding the log4j-acl artifact instantly fixed the problem for me. it routes apache-commons-logging entries from commons logging over to log4j
I'm not sure how you would go about this in grunt but the bridge is what you need.
<!-- Log4J -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jcl</artifactId>
<version>${log4j.version}</version>
</dependency>
Simply add these two lines to you app main:
Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.ERROR);
The necessary import are:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.slf4j.LoggerFactory;
I am using XML configured Log4j2 and Spring Boot. For me, I needed to specify the logging subpackage also, so inside the <Loggers> block:
<Logger name="org.springframework.boot.autoconfigure.logging" level="error" />
You can also use bellow pattern to see the neat logging results in Console.
logging.pattern.console=%clr(%d{yy-MM-dd E HH:mm:ss.SSS}){blue} %clr(%-5p) %clr(%logger{0}){blue} %clr(%m){faint}%n
Click Breakpoints icon and untick checkBox. After Done Re-Run again