MinBox Logging
MinBox Logging is a distributed, zero-intrusion link log analysis framework, which supports configuration and use under Spring Cloud micro-service architecture. It encapsulates RestTemplate and OpenFeign to transmit link information.
Zero invasive
MinBox Logging does not need to use annotation configuration to collect link logs, but simply configure the relevant address or service name of Minbox Logging Admin after adding dependencies. Every time a request is received, the link log details corresponding to the request will be automatically reported to MinBox Logging Admin for subsequent analysis and alarm notification.
Source address
https://gitee.com/minbox-projects/minbox-logging
I. concept
1. Link Architecture Diagram
In one request, the link number (TraceId) of each service (MicroService) that passes through is consistent, and links between the upper and lower levels are connected by SpanID and ParentSpanID.
2. Problems encountered in submitting applications
If you encounter problems in the integration process, please submit issues and address: Create Issues
3. ApiBoot integration practice example
ApiBoot, as the best component integration solution for MinBox open source organizations, will be integrated in the first place minbox-projects New released components in open source organizations, MinBox Logging integration practices, visit ApiBoot Source code For more information on the source code, see org.minbox.framework.api.boot.autoconfigure.logging.
II. Configuring Client
4. Enabling Client
The @EnableLoggingClient annotation is provided in the minbox-logging-spring-context dependency to enable the client, and the beans needed to automatically register the Logging Client runtime through @Import after using the annotation are configured.
@ The EnableLoggingClient uses an example as follows:
@SpringBootApplication @EnableLoggingClient public class ApiBootLoggingApplication { /** * logger instance */ static Logger logger = LoggerFactory.getLogger(ApiBootLoggingApplication.class); public static void main(String[] args) { SpringApplication.run(ApiBootLoggingApplication.class, args); logger.info("{}Service Startup Successful.", "ApiBoot Logging Client"); } }
5. Transmitting Link Information
Each request will generate a link information, while the previous mutual access of link units (Span) currently takes the form of http, rpc and so on as the main proportion.
In the transmission of link information (Trace), the link information number (TraceID) and parent unit number (Parent SpanID) in the request header are extracted from the Logging Client, through which the whole link can bind the relationship between the upper and lower units and the link relationship.
5.1. RestTemplate transmits link information
RestTemplate is a request encapsulation object provided by Spring Web component. It can be used to send a request in a specified way to the target address. It can carry header information to transmit authentication information, request, response and other information.
Logging Client uses RestTemplate's interceptor to transfer link (Trace) information to the header of the request to the next unit (Span).
Logging Client has provided a RestTemplate interceptor implementation class LoggingRestTemplate Interceptor, instantiated in the LoggingFactoryBean#afterPropertiesSet method and set up an interceptor. When logging Client reports requests for log information, it sends requests to Admin through LoggingFactoryBean#restTemplate, so it only needs to instantiate LoggingFactory. Bean is OK.
5.2. OpenFeign Transmit Link Information
OpenFeign is an implementation of Spring Cloud calling methods between services, sending requests and obtaining response content according to interface configuration information.
Logging Client also uses the interceptor provided by OpenFeign to write the link (Trace) information to the request header of the mutual invocation of services for delivery to the next service.
Logging Client provides the Request Interceptor interface to implement the class LoggingOpenFeignInterceptor to complete link information transmission. OpenFeign automatically retrieves the implementation class instance of Request Interceptor interface in Spring IOC container, and calls the application method of Request Interceptor implementation class to complete the interception business processing each time requests are made through OpenFeign.
6. Discover Admin and report to the log
By default, the Logging Client does not persist the request log information locally, but reports the local generated request log details to Logging Admin for storage, analysis and so on.
Logging Client provides a Logging AdminDiscovery # lookup interface method to discover Admin addresses.
6.1. Admin found at specified address
Logging Client gets the specified Admin address through Logging Admin Discovery, one of its implementation classes, Logging Appoint Admin Discovery.
Below is an example of ApiBoot configuration using Logging Appoint Admin Discovery practice.
See the source code for details, <a href="https://gitee.com/minbox-projects/api-boot/blob/master/api-boot-project/api-boot-autoconfigure/src/main/java/org/minbox/framework/api/boot/autoconfigure/logging/ApitLoggingAdmingConfiguration.java"="_blank">ApitLogging AdmingAppointment Configuration.java":
/** * ApiBoot Logging Admin Config Discovery * Multiple Use "," Separation * * @return LoggingAdminDiscovery */ @Bean @ConditionalOnMissingBean public LoggingAppointAdminDiscovery loggingConfigAdminDiscovery() { String[] adminAddressArray = apiBootLoggingProperties.getAdmin().getServerAddress().split(","); LoggingAppointAdminDiscovery appointAdminDiscovery = new LoggingAppointAdminDiscovery(adminAddressArray); return appointAdminDiscovery; }
The Logging Appoint Admin Discovery constructor needs to provide an array of Logging Admin addresses in the form of: IP (IP address): port (port number), and does not need to add any http, https prefixes.
6.1.1. Multiple Admin Address Load Balancing Configuration
If we pass multiple Logging Admin addresses when we create a Logging AppointAdminDiscovery object, for example:
@Bean @ConditionalOnMissingBean public LoggingAppointAdminDiscovery loggingConfigAdminDiscovery() { // Initialize Logging Admin address list String[] adminAddressArray = {"127.0.0.1:8080,127.0.0.1:9090"}; LoggingAppointAdminDiscovery appointAdminDiscovery = new LoggingAppointAdminDiscovery(adminAddressArray); return appointAdminDiscovery; }
As shown above, I started two Logging Admin to receive the request log information collected by Logging Client and execute storage. What Load Blanace (Load Balancing) strategy does Logging Client use to select the reported Logging Admin node?
Logging Client provides LoadBalance Strategy load balancing policy interface, while the internal implementation of two strategies are Random Weighted Strategy and SmoothWeighted Round Robin Strategy.
Logging Client defaults to SmoothWeighted Round Robin Strategy (Smooth Polling Weight) load balancing strategy.
6.1.2. Stochastic Weighted Load Strategy
Although LoggingAppoint Admin Discovery instantiates the smooth polling load strategy by default in the constructor, we can certainly set specific policies through the LoggingAppoint AdminDiscovery# setLoadBalance Strategy method. The random weight strategy is set as follows:
@Bean @ConditionalOnMissingBean public LoggingAppointAdminDiscovery loggingConfigAdminDiscovery() { // Initialize Logging Admin address list String[] adminAddressArray = {"127.0.0.1:8080,127.0.0.1:9090"}; LoggingAppointAdminDiscovery appointAdminDiscovery = new LoggingAppointAdminDiscovery(adminAddressArray); // Instantiate random weight policy RandomWeightedStrategy randomWeightedStrategy = new RandomWeightedStrategy(); // Setting Load Balancing Strategy appointAdminDiscovery.setLoadBalanceStrategy(randomWeightedStrategy); return appointAdminDiscovery; }
Random Weighted Strategy (Random Weighted Load Strategy) is a random allocation to select a specified Logging Admin address. In the above example, the result of random weight may be as follows:
Logging Admin address obtained by random weight: 127.0.0.1:8080 127.0.0.1:8080 127.0.0.1:9090 127.0.0.1:8080 127.0.0.1:9090 127.0.0.1:9090 127.0.0.1:9090
6.1.3. Smooth Polling Weight Load Strategy
SmoothWeighted Round Robin Strategy (SmoothWeighted Round Robin Strategy) is a smooth allocation of specified Logging Admin addresses. In the above example, the result of smoothed polling weights is as follows:
Logging Admin address obtained by smoothing polling weight: 127.0.0.1:8080 127.0.0.1:9090 127.0.0.1:8080 127.0.0.1:9090 127.0.0.1:8080 127.0.0.1:9090
6.2. Service Registry Discovered Admin
When using Spring Cloud MicroService deployment mode, Logging Admin can be registered as a separate service to Service Registry Center (service registry, such as Eureka, Zookeeper, Consul, Nacos Discovery, etc.), so that Logging Client can complete the discovery of Logging Admin through the discovery interface of service registration, and report the address after obtaining it. Log.
Logging Client provides service discovery of integrated service registry to realize Logging Registry Center Admin Discovery. By configuring and instantiating this class and putting it into Spring IOC, it can automatically obtain Logging Admin information from service registry.
The ApiBoot configuration uses the Logging Registry Center AdminDiscovery practice example, as detailed in the source code, <a href= "https://gitee.com/minbox-projects/api-boot/blob/master/api-boot-project/api-boot-autoconfigure/src/main/java/org/minbox/framework/api/boot/autoconfigure/logging/ABootDiscovery Configuration"="_AdmingDiscovery Configuration.java". YAutoConfiguration </a>.
/** * ApiBoot Logging Admin Registry Center Discovery * @param loadBalancerClient LoadBalance Client * @return LoggingRegistryCenterAdminDiscovery */ @Bean @ConditionalOnMissingBean public LoggingRegistryCenterAdminDiscovery loggingRegistryCenterAdminDiscovery(LoadBalancerClient loadBalancerClient) { LoggingRegistryCenterAdminDiscovery registryCenterAdminDiscovery = new LoggingRegistryCenterAdminDiscovery(apiBootLoggingProperties.getDiscovery().getServiceId(), loadBalancerClient); return registryCenterAdminDiscovery; }
LoadBalancer Client is a Spring Cloud load balancing client object. By automatically configuring Spring Cloud dependencies and putting them into Spring IOC, the LoadBalancer Client can find a service object named Service Instance that is available for load balancing.
7. Delayed reporting log
Logging Client by default uses just (direct reporting) to report the collected request logs. Every time a request log is generated, it will report to Logging Admin in real time. Sometimes the demand changes greatly, such as reducing the pressure of Logging Admin. At this time, it may report 20 request logs to Logging Admin at a time.
In view of this business situation, the Logging Client provides a regular reporting method.
7.1. Configuration of reporting methods
The default value is modified by LoggingFactoryBean#setReportAway method with the parameter of org.minbox.framework.logging.core.ReportAway enumeration. The modification is as follows:
// Set up the reporting mode as follows:timing factoryBean.setReportAway(ReportAway.timing);
7.2. Set the number of logs for a single report
The default number of request logs for a single report is: 10.
Modify the default values through the LoggingFactoryBean#setNumberOfRequestLog method, as follows:
// Set the number of request logs per report factoryBean.setNumberOfRequestLog(20);
7.3. Set the interval between reporting logs
The default interval for reporting logs is: 5 seconds.
Modify the default values through the LoggingFactoryBean#setReportIntervalSecond method, as follows:
// Time interval for equipment reporting in seconds factoryBean.setReportIntervalSecond(5);
8. Custom TraceID Generation Rules
Logging Client uses the string generated by UUID as TraceId (link number) by default, and modifies the default generation rules by LoggingFactoryBean#setTraceGenerator method. The custom policy needs to implement the LoggingTraceGenerator interface, as follows:
/** * Custom link number (TraceID) {@link Logging TraceGenerator} * * @author Heng Yu junior */ public class CustomerTraceIdGenerator implements LoggingTraceGenerator { @Override public String createTraceId() throws MinBoxLoggingException { return UUID.randomUUID().toString().replace("-", ""); } }
Setting up a custom policy is as follows:
// Create custom policy objects CustomerTraceIdGenerator customerTraceIdGenerator = new CustomerTraceIdGenerator(); // Setting up a policy for using custom generation of TraceID factoryBean.setTraceGenerator(customerTraceIdGenerator);
9. Custom SpanID Generation Rules
Logging Client uses the string generated by UUID as SpanId (unit number) by default, and modifies the default generation rules by LoggingFactoryBean#setSpanGenerator method. The custom policy needs to implement the LoggingSpanGenerator interface, as follows:
/** * Custom unit number (SpanID) {@link LoggingSpanGenerator} * * @author Heng Yu junior */ public class CustomerSpanIdGenerator implements LoggingSpanGenerator { @Override public String createSpanId() throws MinBoxLoggingException { String currentTime = String.valueOf(System.currentTimeMillis()); return String.format("%s-%s", "span", currentTime); } }
Settings to use custom policies are as follows:
// Create custom policy objects CustomerSpanIdGenerator customerSpanIdGenerator = new CustomerSpanIdGenerator(); // Setting up a policy for using custom SpanID generation factoryBean.setSpanGenerator(customerSpanIdGenerator);
10. Exclude partial paths without reporting logs
Logging Client excludes / error path from reporting logs by default. If there are some frequently accessed interfaces for business services and the interfaces do not involve business requests, it is recommended that these requests be excluded. For example, after integrating Spring Boot Admin, frequent access / actuator/health will be used to check the health of the service.
Additional exclusion paths are implemented through the LoggingFactoryBean#setIgnorePaths method. Note that additions are not replacements, so / error is always in the exclusion list. Configure exclusion paths as follows:
// List of paths to be excluded String[] ignorePaths = new String[]{ "/actuator/health", "/index", "/test" }; // Setting Excluded Path List factoryBean.setIgnorePaths(ignorePaths);
11. Safety Reporting Log
Distributed log acquisition and storage will inevitably have security problems, so this problem has been solved in Logging Admin server. Logging Admin completes Basic Auth authentication by integrating Spring Security configuration user name and password.
When Logging Client initiates a report request, it extracts the Basic Auth authentication information in the Logging Admin path and transmits the authentication information through header.
11.1. Specify Admin Address Configuration
If Logging Admin Discovery is configured in Logging Appoint Admin Discovery mode, the user name and password information of Basic Auth need to be carried when the constructor initializes the Logging Admin address, as follows:
@Bean @ConditionalOnMissingBean public LoggingAppointAdminDiscovery loggingConfigAdminDiscovery() { // Initialize Logging Admin address list String[] adminAddressArray = {"user:123@127.0.0.1:8080,user:123@127.0.0.1:9090"}; LoggingAppointAdminDiscovery appointAdminDiscovery = new LoggingAppointAdminDiscovery(adminAddressArray); return appointAdminDiscovery; }
In the above example, you can see that Basic Auth is configured in username:password@IP:Port format, where user is the user name and 123 is the user's password.
11.2. Service Registry Configuration
If the Logging Admin Service Address Discovery is configured in Logging Registry Center Admin Discovery mode, the configuration is as follows:
/** * ApiBoot Logging Admin Registry Center Discovery * setting basic auth username if not empty {@link LoggingRegistryCenterAdminDiscovery#setUsername(String)} * setting basic auth password if not empty {@link LoggingRegistryCenterAdminDiscovery#setPassword(String)} * * @param loadBalancerClient LoadBalance Client * @return LoggingRegistryCenterAdminDiscovery */ @Bean @ConditionalOnMissingBean public LoggingRegistryCenterAdminDiscovery loggingRegistryCenterAdminDiscovery(LoadBalancerClient loadBalancerClient) { LoggingRegistryCenterAdminDiscovery registryCenterAdminDiscovery = new LoggingRegistryCenterAdminDiscovery(apiBootLoggingProperties.getDiscovery().getServiceId(), loadBalancerClient); // User name String basicAuthUserName = apiBootLoggingProperties.getDiscovery().getUsername(); if (ObjectUtils.isEmpty(basicAuthUserName)) { registryCenterAdminDiscovery.setUsername(basicAuthUserName); } // Password String basicAuthPassword = apiBootLoggingProperties.getDiscovery().getPassword(); if (!ObjectUtils.isEmpty(basicAuthPassword)) { registryCenterAdminDiscovery.setPassword(basicAuthPassword); } return registryCenterAdminDiscovery; }
As shown in the example above, the user name is set according to the LoggingRegistry Center AdminDiscovery # setUsername method, and the password is set according to the LoggingRegistry Center AdminDiscovery # setPassword method.
12. Console Displays Update Log
By default, the Logging Client does not print the request log information to be reported in the console. It can be set by the Logging Factitory # setShowConsoleLog method, as shown below:
// Set up logs to output reports on the console factoryBean.setShowConsoleLog(true);
13. Formatting Console Displays Update Log
Logging Client does not format the json string by default when printing the reported request log on the console. It is set according to the LoggingFactoryBean#setFormatConsoleLog method, as follows:
// Set the log to format the output of the report factoryBean.setFormatConsoleLog(true);
14. Custom log notification
Logging Client provides log notification function. It only needs to implement the Logging Notice interface to obtain the detailed object of request log for each report, and to process the log by itself. As follows:
/** * Custom Log Notification * @author Heng Yu junior */ @Component public class CustomerLoggingNotice implements LoggingNotice { /** * Notification method * Handling custom business logic * @param minBoxLog */ @Override public void notice(MinBoxLog minBoxLog) { System.out.println(minBoxLog.getTraceId()); // Custom Business Processing } /** * Notification execution priority * {@link #getOrder()}The smaller the method return value, the higher the priority * * @return */ @Override public int getOrder() { return 1; } }
14.1. Built-in log notifications
Logging Client provides specific implementation of log notification, namely: Logging Local Notice, Logging AdminNotice.
Log Notification Implementation Class | Function |
---|---|
LoggingLocalNotice | LoggingLocalNotice log notification is used to display and format log object details in the console with priority of Integer.MIN_VALUE. The source code is detailed in org.minbox.framework.logging.client.notice.support.LoggingLocalNotice. |
LoggingAdminNotice | LoggingAdminNotice log notification is used to report log information to Logging Admin with priority of Integer.MIN_VALUE+1. See the source code at org.minbox.framework.logging.client.notice.support.LoggingAdminNotice. |
14.2. Customize multiple log notifications
Logging Client obtains a list of instances of the specified LoggingNotice type from Spring IOC through Application Context, which also supports multi-log notification.
Note: The priority value of the log notification implementation class is not recommended to be repeated.
III. Configuration Server
15. Enabling the server
In the minbox-logging-spring-context dependency, the @EnableLoggingAdmin annotation is provided to enable the server side, and the beans needed to automatically register the Logging Admin runtime through @Import after using the annotation are configured.
@ Enable Logging Admin uses an example as follows:
@SpringBootApplication @EnableLoggingAdmin public class ApiBootLoggingAdminApplication { /** * logger instance */ static Logger logger = LoggerFactory.getLogger(ApiBootLoggingAdminApplication.class); public static void main(String[] args) { SpringApplication.run(ApiBootLoggingAdminApplication.class, args); logger.info("{}Service Startup Successful.", "Logging Admin"); } }
16. Initialization of the database
Logging Admin supports saving request logs reported by Logging Client to a database, and provides a fixed table structure, as follows:
SET NAMES utf8mb4 ; -- -- Table structure for table `logging_service_details` -- DROP TABLE IF EXISTS `logging_service_details`; SET character_set_client = utf8mb4 ; CREATE TABLE `logging_service_details` ( `lsd_id` varchar(36) COLLATE utf8mb4_general_ci NOT NULL, `lsd_service_id` varchar(200) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Reporting service ID,Corresponding spring.application.name Configuration value', `lsd_service_ip` varchar(50) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Reporting service IP address', `lsd_service_port` int(11) DEFAULT NULL COMMENT 'Port number of reporting service', `lsd_last_report_time` timestamp NULL DEFAULT NULL COMMENT 'Last report time, every update', `lsd_create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation time for first reporting', PRIMARY KEY (`lsd_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Details of client services for reporting logs'; -- -- Table structure for table `logging_request_logs` -- DROP TABLE IF EXISTS `logging_request_logs`; SET character_set_client = utf8mb4 ; CREATE TABLE `logging_request_logs` ( `lrl_id` varchar(36) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'Primary key UUID', `lrl_service_detail_id` varchar(36) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Service Details Number, Relevance logging_service_details Primary key', `lrl_trace_id` varchar(36) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'link ID', `lrl_parent_span_id` varchar(36) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Superior span ID', `lrl_span_id` varchar(36) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'span ID', `lrl_start_time` mediumtext COLLATE utf8mb4_general_ci COMMENT 'Request start time', `lrl_end_time` mediumtext COLLATE utf8mb4_general_ci COMMENT 'Request closure time', `lrl_http_status` int(11) DEFAULT NULL COMMENT 'Request response status code', `lrl_request_body` longtext COLLATE utf8mb4_general_ci COMMENT 'Request subject content', `lrl_request_headers` text COLLATE utf8mb4_general_ci COMMENT 'Request header information', `lrl_request_ip` varchar(30) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Initiating the requesting client IP address', `lrl_request_method` varchar(10) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Request mode', `lrl_request_uri` varchar(200) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Request path', `lrl_response_body` longtext COLLATE utf8mb4_general_ci COMMENT 'Response content', `lrl_response_headers` text COLLATE utf8mb4_general_ci COMMENT 'Response header information', `lrl_time_consuming` int(11) DEFAULT NULL COMMENT 'Request time consuming', `lrl_create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Log save time', `lrl_request_params` text COLLATE utf8mb4_general_ci, `lrl_exception_stack` text COLLATE utf8mb4_general_ci, PRIMARY KEY (`lrl_id`), KEY `logging_request_logs_LRL_SERVICE_DETAIL_ID_index` (`lrl_service_detail_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Request log information table';
16.1. Persisting logs to databases
After initializing the table structure required by Logging Admin, we add data source, database driver, persistence framework and other dependencies to the project of integrating Logging Admin, and then configure the database parameters related to the data source. The following is an example of SpringBook project.
16.1.1 Adding required dependencies
The new dependencies of pom.xml are as follows:
<!--ApiBoot Provided persistence framework--> <dependency> <groupId>org.minbox.framework</groupId> <artifactId>api-boot-starter-mybatis-enhance</artifactId> <version>{ApiBoot Latest edition}</version> </dependency> <!--MySQL Database Driver--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency> <!--Hikari data source--> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.2.0</version> </dependency>
Logging Admin does not depend on the persistence framework provided by ApiBoot. It can use any framework dependency. Logging Admin only needs instances of DataSource within itself. It can also customize the creation of DataSource objects into Spring IOC.
16.1.2. Configure data source parameters
spring: # Data source parameters datasource: driver-class-name: com.mysql.cj.jdbc.Driver type: com.zaxxer.hikari.HikariDataSource username: root password: 123456 url: jdbc:mysql://localhost:3306/test
17. Register Admin with Spring Cloud
Logging Admin is added to the SpringBook project as a dependency. We just need to consider how to register the SpringBook project into the Spring Cloud Service Register Center. If you use Eureka as a service registry, please visit my previous article to see <a href="http://blog.yuqiyu.com/spring-cloud-eureka-provider.html"="_blan" K "> Register the microservice provider to Eureka Service Center </a>.
18. Enable security configuration
Logging Admin's security is accomplished with Basic Auth provided by Spring Security.
18.1. Add support for Spring Security
Add the following dependencies in pom.xml of the project:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
18.2. Configuring Secure Users
It is recommended to configure Logging Admin in memory provided by Spring Security. The application.yml configuration file is as follows:
spring: security: user: # User name name: user # Password password: 123
19. Monitor log reporting events
Logging Admin supports customized processing to monitor log information reported by Logging Client. It can store, format, group categorize and so on. Customized event monitoring follows Spring Event/Listener mode, as follows:
/** * Custom Update Log Event {@link ReportLogEvent} Listener * * @author Heng Yu junior */ @Component public class CustomerReportEventListener implements SmartApplicationListener { /** * Determine the event type as {@link ReportLogEvent} * * @param eventType * @return */ @Override public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) { return ReportLogEvent.class == eventType; } /** * Custom Processing Business * * @param event */ @Override public void onApplicationEvent(ApplicationEvent event) { ReportLogEvent reportLogEvent = (ReportLogEvent) event; LoggingClientNotice loggingClientNotice = reportLogEvent.getLogClientNotice(); System.out.println("Logging service Id: " + loggingClientNotice.getClientServiceId()); // Custom Business Processing } }
19.1. Implementation of multi-monitor events
Logging Admin uses Smart Application Listener provided by Spring to listen for ReportLogEvent events, so it only needs to add multiple custom listeners to implement Smart Application Listener interface.
Because Smart Application Listener implements the Ordered interface, it provides the priority configuration method getOrder, which is consistent with the priority strategy of LoggingNotice interface. The smaller the value, the higher the priority.
Detailed understanding of Spring's Event/Listener provides access to <a href= "http://blog.yuqiyu.com/spring-boot-chapter27.html" target="_blank">Spring Boot uses Application Event&Listener to complete business decoupling </a>.
20. LoggingAdminFactoryBean
Logging AdminFactoryBean is a necessary way to configure Logging Admin, through which you can configure Logging Admin in all aspects.
The ApiBoot integrated Logging Admin FactoryBean example is as follows:
/** * instantiation {@link LoggingAdminFactoryBean} * * @param dataSource {@link DataSource} * @return LoggingAdminFactoryBean */ @Bean public LoggingAdminFactoryBean loggingAdminFactoryBean(DataSource dataSource) { LoggingAdminFactoryBean factoryBean = new LoggingAdminFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setShowConsoleReportLog(apiBootLoggingAdminProperties.isShowConsoleReportLog()); factoryBean.setFormatConsoleLogJson(apiBootLoggingAdminProperties.isFormatConsoleLogJson()); logger.info("[LoggingAdminFactoryBean]init successfully."); return factoryBean; }
For the detailed source code of ApiBoot Integrated Logging AdmingFactoryBean, please visit <a href="https://gitee.com/minbox-projects/api-boot/blob/master/api-boot-project/api-boot-autoconfigure/src/main/java/org/minbox/framework/api/boot/configure/logging/n/ApitLogging Automation.Configuration.java"="_Logging>ApitLogging Automation/Configuration>.
20.1. Setting up Data Sources
The Logging AdminFactoryBean #setDataSource method is used to set up the data source of log data that Logging Admin needs to operate on, as follows:
// set up data sources factoryBean.setDataSource(dataSource);
20.2. The console outputs the logs reported
The Logging AdminFactoryBean #setShowConsole Report Log method controls whether log information reported by Logging Client is printed on the console, as follows:
// Set up the console to output Logging Client logs factoryBean.setShowConsoleReportLog(true);
20.3. Format console output log
The log output from the console is formatted using the LoggingAdminFactoryBean#setFormatConsoleLogJson method, as follows:
// Format the log output from the console factoryBean.setFormatConsoleLogJson(true);
This article is a multi-article blog platform OpenWrite Release!