Spring Cloud Spring Boot mybatis distributed microservice cloud architecture (42) Use log4j to implement http request logs into mongodb (1)

Ready to work

You can take the Chapter4-2-4 project as the basis for subsequent experimental transformations. The project implements a simple REST interface, an aspect to the web layer, and records the log content of http requests before and after the aspect of the web layer.

Implemented by custom appender

Idea: The outputter provided by log4j is implemented from the Appender interface. To customize the output of the appender to MongoDB, you only need to inherit the AppenderSkeleton class and implement several methods.

Introduce the driver of mongodb

Introduce the following dependencies in pom.xml

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver</artifactId>
    <version>3.2.2</version>
</dependency>

实现 MongoAppender

Write the MongoAppender class to inherit the AppenderSkeleton, as follows:

public class MongoAppender  extends AppenderSkeleton {

    private MongoClient mongoClient;
    private MongoDatabase mongoDatabase;
    private MongoCollection<BasicDBObject> logsCollection;

    private String connectionUrl;
    private String databaseName;
    private String collectionName;

    @Override
    protected void append(LoggingEvent loggingEvent) {

        if(mongoDatabase == null) {
            MongoClientURI connectionString = new MongoClientURI(connectionUrl);
            mongoClient = new MongoClient(connectionString);
            mongoDatabase = mongoClient.getDatabase(databaseName);
            logsCollection = mongoDatabase.getCollection(collectionName, BasicDBObject.class);
        }
        logsCollection.insertOne((BasicDBObject) loggingEvent.getMessage());

    }

    @Override
    public void close() {
        if(mongoClient != null) {
            mongoClient.close();
        }
    }

    @Override
    public boolean requiresLayout() {
        return false;
    }

    // 省略getter和setter

}
  • Define the configuration parameters of MongoDB, which can be configured through log4j.properties:

    • connectionUrl: string to connect to mongodb
    • databaseName: database name
    • collectionName: collection name
  • Define the connection and operation objects of MongoDB, initialized according to the parameters configured in log4j.properties:

    • mongoClient: connection client of mongodb
    • mongoDatabase: the database for logging
    • logsCollection: collection of logs
  • Override the append function:

    • Create a mongodb connection according to the configuration in log4j.properties
    • LoggingEvent provides getMessage() function to get log message
    • Insert log messages into the configured logging collection
  • Rewrite the close function: close mongodb

  • source code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325856452&siteId=291194637