Detailed steps to install Docker mongoDB 4.2.1 and collect springboot logs

Detailed steps to install Docker mongoDB 4.2.1 and collect springboot logs

1: Install mongodb in docker

Step 1: Install mongodb in docker

[root@iZbp1gp1t778obaz5m8vk8Z /]# docker search mongo
 
[root@iZbp1gp1t778obaz5m8vk8Z /]# docker pull mongo:latest
 
Trying to pull repository docker.io/library/mongo ... 
latest: Pulling from docker.io/library/mongo
f22ccc0b8772: Pull complete 
3cf8fb62ba5f: Pull complete 
e80c964ece6a: Pull complete 
329e632c35b3: Pull complete 
3e1bd1325a3d: Pull complete 
4aa6e3d64a4a: Pull complete 
035bca87b778: Pull complete 
874e4e43cb00: Pull complete 
08cb97662b8b: Pull complete 
f623ce2ba1e1: Pull complete 
f100ac278196: Pull complete 
6f5539f9b3ee: Pull complete 
Digest: sha256:02e9941ddcb949424fa4eb01f9d235da91a5b7b64feb5887eab77e1ef84a3bad
Status: Downloaded newer image for docker.io/mongo:latest
 
[root@iZbp1gp1t778obaz5m8vk8Z /]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
docker.io/mongo latest 3068f6bb852e 5 days ago 493 MB
 
 Specify the version to install. It is recommended not to install the latest version, which is very bad. I like this version [root@iZbp1gp1t778obaz5m8vk8Z ~]$ docker pull mongo:4.2.1

Step 2: Start mongodb in docker

[root@iZbp1gp1t778obaz5m8vk8Z mongodb]# docker run -itd --name mongo --restart=on-failure:10 -d -m 1G --memory-swap 4G -p 27017:27017 -v /data/mongodb:/data/db mongo 
1bcf117db0a8e86840a1acac769338053e8dff25a41bd1488d7a274ea171371a
[root@iZbp1gp1t778obaz5m8vk8Z mongodb]# 
[root@iZbp1gp1t778obaz5m8vk8Z mongodb]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1bcf117db0a8 mongo "docker-entrypoint..." 7 seconds ago Up 7 seconds 0.0.0.0:27017->27017/tcp mongo
 
Here we set it to be visible to new docker users without logging in. Please refer to the previous article to know the parameters after the startup is completed. Let's start to adjust the account
This is the startup of version 4.2.1 [root@iZbp1gp1t778obaz5m8vk8Z mongodb]# docker run -itd --name mongo --restart=on-failure:10 -d -m 1G --memory-swap 4G -p 27017:27017 \
-v /data/mongodb:/data/db \
mongo:4.2.1 --auth
[root@iZbp1gp1t778obaz5m8vk8Z mongodb]# 
[root@iZbp1gp1t778obaz5m8vk8Z mongodb]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1bcf117db0a8 mongo "docker-entrypoint..." 7 seconds ago Up 7 seconds 0.0.0.0:27017->27017/tcp mongo
 
Here we set it to be visible to new docker users without logging in. Please refer to the previous article to know the parameters after the startup is completed. Let's start to adjust the account

《How to operate common docker parameters》

Step 3: Configure user information in mongodb

Create account information for MongoDb [root@iZbp1gp1t778obaz5m8vk8Z mongodb]# docker exec -it mongo mongo admin
MongoDB shell version v4.4.2
connecting to: mongodb://127.0.0.1:27017/admin?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("a2d4a27c-a9dc-4af4-90cb-233e41394d51") }
MongoDB server version: 4.4.2
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
	https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
	https://community.mongodb.com
> db.createUser({ user:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'}]});
Successfully added user:
	"user" : "admin",
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	]
}
> db.auth('admin', '123456')
1
> db.grantRolesToUser("admin", [ { role: "readWrite", db: "admin" } ])
Create account information for MongoDb. If you don't need authentication, you can skip this step, but don't do this in a production environment. # Connect to the command operation interface in docker [root@izwz99z5o9dc90keftqhlrz ~] # docker exec -it mongo mongo admin
 
# Create a user named admin with a password of 123456.
> db.createUser({ user:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'}]});
 
# Try to connect using the user information created above.
> db.auth('admin', '123456')
 
# Grant admin authorization, read and write permissions> db.grantRolesToUser("admin", [ { role: "readWrite", db: "admin" } ])
 
The above is when I first entered
When you enter for the second time, you must follow the rules. You must first enter the guides database, and then add users, otherwise you will not know where you added them. > use guides
#Or give the owner permissions when creating directly> db.createUser({user:"guides",pwd:"123456",roles:[{role:"dbOwner",db:"guides"}]})
#Connect to this account> db.auth('guides','123456')
#Use this account to write a piece of data to the guides database - this document> db.guides.insert({"name":"liuxing", "age":31})

2: Springboot collects logs to mongodb

The collection log is particularly rough

Step 1: Add configuration to pom.xml

<!-- mongodb database operation-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Step 2: Configure the connection in application.yml

#Tell Spring Boot where mongodb should be, no authentication --auth does not require a username and password, remember spring 
 data:
 mongodb:
  host: 47.110.57.115
  port: 27017
  authentication-database: guides
  database: guides
  username: guides
  password: '123456'
  max-connection-idle-time: 1000
  max-connection-per-host: 200
  max-wait-time: 60000
  max-connection-life-time: 0
  connect-timeout: 1000
  socket-timeout: 2000
 
authentication-database 4.0 and above: do not write admin anymore, or 4.2.1
authentication-database: guides

Step 3: Obtaining AOP slice logs

package com.zhx.guides.assistant.dto;
 
import com.zhx.guides.assistant.util.object.TimeHelper;
 
import java.io.Serializable;
import java.util.Date;
 
/**
 * @Date creation time: 2020-12-17 14:33
 * @Author Author name: Liux
 * @Version 1.0
 * @Copyright Copyright by
 * @Direction class description */
public class HttpRequestLog implements Serializable {
 
 public final static String collectName = "guides" ;
 
 private String url ;
 private String httpMethod ;
 private String className ;
 private String methodName ;
 private String ip ;
 private String requestParam ;
 private Date nowTime = TimeHelper.getCurrentDate();
 
 .... get set omitted}
package com.zhx.guides.assistant.web.aspect;
 
import com.alibaba.fastjson.JSONObject;
import com.zhx.guides.assistant.dto.HttpRequestLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import javax.servlet.http.HttpServletRequest;
 
/**
 * @Class WebLogAspect
 * @Version 1.0
 * @Date creation time: 2020-03-03 10:05
 * @Copyright Copyright by company
 * @Direction class description */
@Aspect
@Component
public class WebLogAspect {
 
 @Autowired
 private MongoTemplate mongoTemplate;
 
 private final static Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
 
 /** Take all requests defined in the controller package as the entry point*/
 @Pointcut("execution(public * com.zhx.guides.assistant.interfaces.controller..*.*(..))")
 public void webLog() {}
 
 /**
  * Weaving before the pointcut * @param joinPoint
  * @throws Throwable
  */
 @Before("webLog()")
 public void doBefore(JoinPoint joinPoint) throws Throwable {
  // Start printing request log ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  HttpServletRequest request = attributes.getRequest();
 
  HttpRequestLog httpRequestLog = new HttpRequestLog();
  httpRequestLog.setUrl( request.getRequestURL().toString() );
  httpRequestLog.setHttpMethod( request.getMethod() );
  httpRequestLog.setClassName( joinPoint.getSignature().getDeclaringTypeName() );
  httpRequestLog.setMethodName( joinPoint.getSignature().getName());
  httpRequestLog.setIp( request.getRemoteAddr() );
 
  // Print request related parameters logger.info("======================= Start ======================");
  // Print request url
  logger.info("URL : {}", httpRequestLog.getUrl() );
  // Print Http method
  logger.info("HTTP Method : {}", httpRequestLog.getHttpMethod());
  // Print the full path of the controller call and the execution method logger.info("Class Method : {}.{}", httpRequestLog.getClassName() , httpRequestLog.getMethodName());
  // Print the requested IP
  logger.info("IP : {}", httpRequestLog.getIp() );
  //Print request input parameter try {
   Object requestParam = joinPoint.getArgs();
   httpRequestLog.setRequestParam( JSONObject.toJSONString(requestParam) );
   logger.info("Parameters: {}", httpRequestLog.getRequestParam());
  }catch (Exception e){
   logger.info("Parameter printing failed, exception: {}", e.getMessage());
  }finally {
   httpRequestLog.setClassName( null );
   try{mongoTemplate.save( httpRequestLog , HttpRequestLog.collectName );}catch (Exception e){}
  }
 }
 
 /**
  * Weave in after the pointcut * @throws Throwable
  */
 @After("webLog()")
 public void doAfter() throws Throwable {
  logger.info("======================== End ======================");
 }
 
 /**
  * Wrap around * @param proceedingJoinPoint
  * @return
  * @throws Throwable
  */
 @Around("webLog()")
 public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
  long startTime = System.currentTimeMillis();
  Object result = proceedingJoinPoint.proceed();
  // Print out the parameters logger.info("return value: {}", JSONObject.toJSONString(result));
  // Execution time logger.info("Time: {} ms", System.currentTimeMillis() - startTime);
  return result;
 }
 
}
package com.zhx.guides.assistant.util.object;
 
import org.apache.commons.lang.StringUtils;
 
import java.util.Date;
 
/**
 * @Class TimeHelper
 * @Version 1.0
 * @Date creation time: 2018/12/21 09:26
 * @Copyright Copyright by
 * @Direction class description */
public class TimeHelper { 
 
 /**
  *Current time* @return
  */
 public static Date getCurrentDate(){
  Calendar calendar = Calendar.getInstance();
  return calendar.getTime();
 }
 
}

Three: Look at the effect of storing logs

Note : Please note the mongodb version used: 4.2.1. Configure and use them in sequence.

If you are using the latest version, there may be problems with various permissions not being passed, so please switch to the 4.2.1 stable version. Using the latest version is a bit like being a guinea pig.

This is the end of this article about installing Docker mongoDB 4.2.1 and collecting springboot logs. For more information about installing Docker mongoDB and collecting springboot logs, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of how to install mongodb using docker on linux
  • How to install the latest version of MongoDB using Docker
  • Install Mongo4.2 and client tools to connect to Mongo under Docker

<<:  VUE Getting Started Learning Event Handling

>>:  Comprehensive analysis of isolation levels in MySQL

Recommend

Teach you to connect to MySQL database using eclipse

Preface Since errors always occur, record the pro...

How to use JS to parse the excel content in the clipboard

Table of contents Preface 1. Paste Events and Cli...

Detailed explanation of MySQL clustered index and non-clustered index

1. Clustered Index Table data is stored in the or...

JavaScript counts the number of times a character appears

This article example shares the specific code of ...

Implementation of formatting partitions and mounting in Centos7

Linux often encounters situations such as adding ...

How to choose the right MySQL datetime type to store your time

When building a database and writing a program, i...

Use Typescript configuration steps in Vue

Table of contents 1. TypeScript is introduced int...

Example of using UserMap in IMG

usemap is an attribute of the <img> tag, use...

Detailed explanation of Vue-router nested routing

Table of contents step 1. Configure routing rules...

Page Speed ​​Optimization at a Glance

I believe that the Internet has become an increas...

Use of Linux gzip command

1. Command Introduction The gzip (GNU zip) comman...

Tools to convert static websites into RSS

<br /> This article is translated from allwe...

Methods and steps to access Baidu Maps API with JavaScript

Table of contents 1. Baidu Map API Access 2. Usin...