一:docker安裝好mongodb
第一步:docker安裝好mongodb
[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
指定版本安裝,建議不要安裝最新的,很坑爹,我喜歡這個版本
[root@iZbp1gp1t778obaz5m8vk8Z ~]$ docker pull mongo:4.2.1
第二步:啟動docker中的mongodb
[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
此處我們設(shè)置為非登錄可見
新docker人請參考前期文章知曉參數(shù),啟動完成后。咱們開始整賬戶
這個是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
此處我們設(shè)置為非登錄可見
新docker人請參考前期文章知曉參數(shù),啟動完成后。咱們開始整賬戶
《docker常見參數(shù)操作方法》
第三步:mongodb 配置好用戶信息
為MongoDb創(chuàng)建賬戶信息
[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" } ])
為MongoDb創(chuàng)建賬戶信息,如果你不需要驗(yàn)證可以不跑這一段,但是生產(chǎn)環(huán)境可不要這么干
# 連接至docker中的命令操作界面
[root@izwz99z5o9dc90keftqhlrz ~]# docker exec -it mongo mongo admin
# 創(chuàng)建一個名為 admin,密碼為 123456的用戶。
> db.createUser({ user:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'}]});
# 嘗試使用上面創(chuàng)建的用戶信息進(jìn)行連接。
> db.auth('admin', '123456')
# 給admin授權(quán)、讀寫權(quán)限
> db.grantRolesToUser("admin", [ { role: "readWrite", db: "admin" } ])
上面是第一次進(jìn)入的時(shí)候
第二次進(jìn)入時(shí),就要守規(guī)矩了.一定要先進(jìn)guides 數(shù)據(jù)庫,再添加用戶,否則不知道你添加到哪里去了
> use guides
#或者直接創(chuàng)建時(shí)給所有者權(quán)限
> db.createUser({user:"guides",pwd:"123456",roles:[{role:"dbOwner",db:"guides"}]})
#連接到此賬戶
> db.auth('guides','123456')
#用此賬戶、寫入一條數(shù)據(jù)到guides數(shù)據(jù)庫-這個文檔
> db.guides.insert({"name":"liuxing", "age":31})
二:springboot采集日志至mongodb
采集日志就特別粗曠了
第一步:pom.xml添加配置
<!-- mongodb數(shù)據(jù)庫操作 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
第二步:application.yml 配置好連接
#告訴Spring Boot應(yīng)該在何處mongodb,沒開驗(yàn)證 --auth 不需要輸入用戶名和密碼,記住
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
4.0以上authentication-database: 不要再寫admin了,或者說4.2.1
authentication-database: guides
第三步:AOP切片日志獲取
package com.zhx.guides.assistant.dto;
import com.zhx.guides.assistant.util.object.TimeHelper;
import java.io.Serializable;
import java.util.Date;
/**
* @Date 創(chuàng)建時(shí)間: 2020-12-17 14:33
* @Author 作者姓名: Liux
* @Version 1.0
* @Copyright Copyright by
* @Direction 類說明
*/
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 省略
}
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 創(chuàng)建時(shí)間:2020-03-03 10:05
* @Copyright Copyright by company
* @Direction 類說明
*/
@Aspect
@Component
public class WebLogAspect {
@Autowired
private MongoTemplate mongoTemplate;
private final static Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
/** 以 controller 包下定義的所有請求為切入點(diǎn) */
@Pointcut("execution(public * com.zhx.guides.assistant.interfaces.controller..*.*(..))")
public void webLog() {}
/**
* 在切點(diǎn)之前織入
* @param joinPoint
* @throws Throwable
*/
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 開始打印請求日志
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() );
// 打印請求相關(guān)參數(shù)
logger.info("======================= Start ======================");
// 打印請求 url
logger.info("URL : {}", httpRequestLog.getUrl() );
// 打印 Http method
logger.info("HTTP Method : {}", httpRequestLog.getHttpMethod() );
// 打印調(diào)用 controller 的全路徑以及執(zhí)行方法
logger.info("Class Method : {}.{}", httpRequestLog.getClassName() , httpRequestLog.getMethodName());
// 打印請求的 IP
logger.info("IP : {}", httpRequestLog.getIp() );
// 打印請求入?yún)?
try {
Object requestParam = joinPoint.getArgs();
httpRequestLog.setRequestParam( JSONObject.toJSONString(requestParam) );
logger.info("參數(shù) : {}", httpRequestLog.getRequestParam() );
}catch (Exception e){
logger.info("參數(shù)打印失敗,異常: {}", e.getMessage() );
}finally {
httpRequestLog.setClassName( null );
try{mongoTemplate.save( httpRequestLog , HttpRequestLog.collectName );}catch (Exception e){}
}
}
/**
* 在切點(diǎn)之后織入
* @throws Throwable
*/
@After("webLog()")
public void doAfter() throws Throwable {
logger.info("======================= End ======================");
}
/**
* 環(huán)繞
* @param proceedingJoinPoint
* @return
* @throws Throwable
*/
@Around("webLog()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = proceedingJoinPoint.proceed();
// 打印出參
logger.info("返回值 : {}", JSONObject.toJSONString(result));
// 執(zhí)行耗時(shí)
logger.info("耗時(shí) : {} 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 創(chuàng)建時(shí)間:2018/12/21 09:26
* @Copyright Copyright by
* @Direction 類說明
*/
public class TimeHelper {
/**
*當(dāng)前時(shí)間
* @return
*/
public static Date getCurrentDate(){
Calendar calendar = Calendar.getInstance();
return calendar.getTime();
}
}
三:看看存儲日志的效果
備注:請注意使用的mongodb版本:4.2.1 依次配置使用即可
如果你使用的最新版本,有可能發(fā)生各種 權(quán)限不能通過的問題,那么請切換至4.2.1穩(wěn)定版本,用最新版本有點(diǎn)當(dāng)小白鼠的感覺。
到此這篇關(guān)于Docker mongoDB 4.2.1 安裝并收集springboot日志的文章就介紹到這了,更多相關(guān)Docker安裝mongoDB并收集springboot日志內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!