Springboot dynamically modifies log level operations

Time:2022-5-6

preface

In order to reduce the performance impact of frequent log printing, the log level set in online environment is generally relatively high. When a production problem needs troubleshooting, you may need to appropriately reduce the log level (such as debug) to print more log information to help locate the problem.

The traditional practice is generally:

1. Modify log level in configuration

2. Restart application

3. Check the error log for problem recurrence and troubleshooting

This process needs to restart the application, which is troublesome and inefficient. Moreover, for large-scale online projects, it is impossible to stop and restart at will. Is there a way to dynamically modify the log level without restarting the application?

Next, let Lao Wan teach you how to dynamically modify the log level through the actor component of springboot.

1、 Add dependency


<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2、 Configure the exposed ports of the actor

#Enable actor port
management.endpoints.enabled-by-default=fasle
#Set the access root path of the actor. The default is / actor
management.endpoints.web.base-path=/message
#Enabled endpoints
management.endpoints.web.exposure.include=loggers

Here, I modified the default access path of the actor / actor to / message, so that it is consistent with the basic access path of the project.

To enable port configuration:

Method 1: (recommended)


management.endpoints.web.exposure.include=loggers

Mode 2: (this test is not effective)


management.endpoint.loggers.enabled=true

Supplement: how to disable info port


management.endpoints.enabled-by-default=false
management.endpoint.info.enabled=true

The actor component is one of the four major components of spring boot. It has powerful functions. You can find some information on the Internet for further understanding.

Endpoint port description of actor:

ID describe Enabled by default
auditevents Displays audit event information for the current application Yes
beans Displays a complete list of all spring beans in an application Yes
conditions Displays the status of configuration classes and auto configuration classes and the reasons why they are applied or not applied Yes
configprops Displays a collection list of all @ configurationproperties Yes
env Displays the properties of the configurableenvironment from spring Yes
flyway Displays the database migration path, if any Yes
health Display the health information of the application (a simple ‘status’ is displayed when accessing with an unauthenticated connection, and all information details are displayed when accessing with an authenticated connection) Yes
info Display any application information Yes
liquibase Show any liquibase database migration paths, if any Yes
metrics Display the metrics information of the current application Yes
mappings Displays a collection list of all @ requestmapping paths Yes
scheduledtasks Displays scheduled tasks in the application Yes
sessions Allows retrieval and deletion of user sessions from the session store supported by spring sessions. Not available when using spring session support for reactive web applications. Yes
shutdown Allow apps to close gracefully (not enabled by default) No
threaddump Execute a thread dump Yes

If you use a web application (spring MVC, spring Webflux, or Jersey), you can also use the following endpoints:

ID describe Enabled by default
heapdum Returns a gzip compressed hprof heap dump file Yes
jolokia Expose JMX beans via HTTP (Webflux is not available when jolokia is on the classpath) Yes
logfile Return the contents of the log file (if the logging.file or logging.path attribute is set), and support the use of HTTP range header to receive some information of the contents of the log file Yes
prometheus Displays metrics information in a format that can be captured by the Prometheus server Yes

To change which endpoints are exposed, use the following technology specific include and exclude properties:

Property Default
management.endpoints.jmx.exposure.exclude *
management.endpoints.jmx.exposure.include *
management.endpoints.web.exposure.exclude *
management.endpoints.web.exposure.include info, health

includeProperty lists the ID of the exposed endpoint,

excludeProperty lists the IDs of endpoints that should not be exposed

excludeAttribute takes precedence over include attribute. Both the include and exclude properties can be configured using the endpoint ID list.

*Can be used to select all endpoints.

For example, to expose everything over HTTP except Env and beans endpoints, use the following properties:


management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env,beans

3、 Turn off authentication

Generally, we will combine the actor with the spring security authentication component to prevent these function ports from being called casually. Since this is a function demonstration, first release the authority authentication of the relevant ports of the actor.

In addition, if spring security exists, you need to add a custom security configuration to allow unauthenticated access to endpoints, as shown in the following example: release all endpoint endpoints for matching


@Configuration
public class ActuatorSecurity extends WebSecurityConfigurerAdapter {
 
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests()
    .anyRequest().permitAll()
}

}

4、 View the log level through the / loggers port

Request link: http://localhost:8090/message/loggers

Pay attention to what I said above. I adjusted management endpoints. web. base-path=/message。 If this parameter is not set, the default / actor is used to access it.

在这里插入图片描述

5、 Initiate HTTP request to modify log level

Here is a demo to modify the directory com wxswj. provider. message. The log level of the controller is debug

The request type is post and the parameter format is JSON


curl -H "Content-Type: application/json" -X POST --data 
'
{
    "configuredLevel": "DEBUG"
}
' 
http://localhost:8090/message/loggers/com.wxswj.provider.message.controller

You can initiate HTTP requests on the server through curl or through postman.


curl -H "Content-Type: application/json" -X POST --data '{"configuredLevel": "DEBUG"}' http://localhost:8090/loggers/com.wxswj.provider.message.controller

6、 Query log level modification results

http://localhost:8090/message/loggers/com.wxswj.provider.message.controller


{
"configuredLevel": "DEBUG",
"effectiveLevel": "DEBUG"
}

Indicates that our request to modify the log level takes effect.

summary

By integrating the actor component of spring boot and exposing the corresponding / loggers port, we can easily adjust the log level of the system dynamically without restarting the project.

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer.

Recommended Today

What is the economic model construction node of adaoracle oracle

Through the feed price and API on the connection chain, adamorcorporation can access any type of API interface, realize more fair and just data acquisition and service ecology, provide reliable data for DAPP, and build a more reliable, convenient and lower cost Oracle service platform. With its leading technical level, adamorcorporation has overcome the problems […]