In microservice development, logging is a very basic task, recording interface request log information, which helps us troubleshoot problems and help reproduce problems. The log content includes the link, request method, useragent, header, current microservice node machine IP, node machine name, running environment, requester IP, time consumption, and other information.
Using the Filter blocker of the Spring Cloud framework, you can intercept the request information records of all interfaces and persist the request records in MongoDB.
Interface log structure
First, create a new object and define the structure of the log, the code is as follows:
Log filter
Create a new RequestLoggerFilter filter, inherit the Filter interface, and implement the doFilter method, this filter has the highest priority, and the filter priority can be set through the @Order annotation.Filters log POST/PUT commits (excludes multipart/form-data file commit records), the code is as follows:
Logs persist to MongoDB
In order not to affect the normal use of the interface, the interface log will be dropped into the thread-safe queue, the program will open a thread, the thread will consume the data in the queue, store the data in MongoDB, and use maven to introduce dependencies.
For more information about mongodb, see org.springframework.boot.autoconfigure.mongo.MongoProperties
application.yml The configuration is as follows:
URI format: username: root, password: aaaaaaa, database address: 127.0.0.1, port number: 27017, database name: test For example: mongodb://root:aaaaaa@127.0.0.1:27017/test
IfThe username or password contains a special symbol, so use the URL encoding, otherwise an error will be reported!
Call MongoTemplate to persist data into the database with the following code:
(End)
|