首页>运维>Docker> 文章正文

Docker mongoDB 4.2.1 安装并收集springboot日志的步骤详解

来源: Docker 2天之前 阅读: 9
一:docker安装好mongodb 第一步:docker安装好mongodb [root@iZbp1gp1t778obaz5m8vk8Z/]#dockersearchmongo

一:docker安装好mongodb

第一步:docker安装好mongodb

[root@iZbp1gp1t778obaz5m8vk8Z/]#dockersearchmongo

[root@iZbp1gp1t778obaz5m8vk8Z/]#dockerpullmongo:latest

Tryingtopullrepositorydocker.io/library/mongo...

latest:Pullingfromdocker.io/library/mongo

f22ccc0b8772:Pullcomplete

3cf8fb62ba5f:Pullcomplete

e80c964ece6a:Pullcomplete

329e632c35b3:Pullcomplete

3e1bd1325a3d:Pullcomplete

4aa6e3d64a4a:Pullcomplete

035bca87b778:Pullcomplete

874e4e43cb00:Pullcomplete

08cb97662b8b:Pullcomplete

f623ce2ba1e1:Pullcomplete

f100ac278196:Pullcomplete

6f5539f9b3ee:Pullcomplete

Digest:sha256:02e9941ddcb949424fa4eb01f9d235da91a5b7b64feb5887eab77e1ef84a3bad

Status:Downloadednewerimagefordocker.io/mongo:latest

[root@iZbp1gp1t778obaz5m8vk8Z/]#dockerimages

REPOSITORYTAGIMAGEIDCREATEDSIZE

docker.io/mongolatest3068f6bb852e5daysago493MB

指定版本安装,建议不要安装最新的,很坑爹,我喜欢这个版本

[root@iZbp1gp1t778obaz5m8vk8Z~]$dockerpullmongo:4.2.1

第二步:启动docker中的mongodb

[root@iZbp1gp1t778obaz5m8vk8Zmongodb]#dockerrun-itd--namemongo--restart=on-failure:10-d-m1G--memory-swap4G-p27017:27017-v/data/mongodb:/data/dbmongo

1bcf117db0a8e86840a1acac769338053e8dff25a41bd1488d7a274ea171371a

[root@iZbp1gp1t778obaz5m8vk8Zmongodb]#

[root@iZbp1gp1t778obaz5m8vk8Zmongodb]#dockerps-a

CONTAINERIDIMAGECOMMANDCREATEDSTATUSPORTSNAMES

1bcf117db0a8mongo"docker-entrypoint..."7secondsagoUp7seconds0.0.0.0:27017->27017/tcpmongo

此处我们设置为非登录可见

新docker人请参考前期文章知晓参数,启动完成后。咱们开始整账户

这个是4.2.1版本的启动

[root@iZbp1gp1t778obaz5m8vk8Zmongodb]#dockerrun-itd--namemongo--restart=on-failure:10-d-m1G--memory-swap4G-p27017:27017

-v/data/mongodb:/data/db

mongo:4.2.1--auth

[root@iZbp1gp1t778obaz5m8vk8Zmongodb]#

[root@iZbp1gp1t778obaz5m8vk8Zmongodb]#dockerps-a

CONTAINERIDIMAGECOMMANDCREATEDSTATUSPORTSNAMES

1bcf117db0a8mongo"docker-entrypoint..."7secondsagoUp7seconds0.0.0.0:27017->27017/tcpmongo

此处我们设置为非登录可见

新docker人请参考前期文章知晓参数,启动完成后。咱们开始整账户

《docker常见参数操作方法》

第三步:mongodb配置好用户信息

为MongoDb创建账户信息

[root@iZbp1gp1t778obaz5m8vk8Zmongodb]#dockerexec-itmongomongoadmin

MongoDBshellversionv4.4.2

connectingto:mongodb://127.0.0.1:27017/admin?compressors=disabled&gssapiServiceName=mongodb

Implicitsession:session{"id":UUID("a2d4a27c-a9dc-4af4-90cb-233e41394d51")}

MongoDBserverversion:4.4.2

WelcometotheMongoDBshell.

Forinteractivehelp,type"help".

Formorecomprehensivedocumentation,see

http://docs.mongodb.com/

Questions?TrytheMongoDBDeveloperCommunityForums

http://community.mongodb.com

>db.createUser({user:'admin',pwd:'123456',roles:[{role:'userAdminAnyDatabase',db:'admin'}]});

Successfullyaddeduser:{

"user":"admin",

"roles":[

{

"role":"userAdminAnyDatabase",

"db":"admin"

}

]

}

>db.auth('admin','123456')

1

>db.grantRolesToUser("admin",[{role:"readWrite",db:"admin"}])

为MongoDb创建账户信息,如果你不需要验证可以不跑这一段,但是生产环境可不要这么干

#连接至docker中的命令操作界面

[root@izwz99z5o9dc90keftqhlrz~]#dockerexec-itmongomongoadmin

#创建一个名为admin,密码为123456的用户。

>db.createUser({user:'admin',pwd:'123456',roles:[{role:'userAdminAnyDatabase',db:'admin'}]});

#尝试使用上面创建的用户信息进行连接。

>db.auth('admin','123456')

#给admin授权、读写权限

>db.grantRolesToUser("admin",[{role:"readWrite",db:"admin"}])

上面是第一次进入的时候

第二次进入时,就要守规矩了.一定要先进guides数据库,再添加用户,否则不知道你添加到哪里去了

>useguides

#或者直接创建时给所有者权限

>db.createUser({user:"guides",pwd:"123456",roles:[{role:"dbOwner",db:"guides"}]})

#连接到此账户

>db.auth('guides','123456')

#用此账户、写入一条数据到guides数据库-这个文档

>db.guides.insert({"name":"liuxing","age":31})

二:springboot采集日志至mongodb

采集日志就特别粗旷了

第一步:pom.xml添加配置

<!--mongodb数据库操作-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-mongodb</artifactId>

</dependency>

第二步:application.yml配置好连接

#告诉SpringBoot应该在何处mongodb,没开验证--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切片日志获取

packagecom.zhx.guides.assistant.dto;

importcom.zhx.guides.assistant.util.object.TimeHelper;

importjava.io.Serializable;

importjava.util.Date;

/**

*@Date创建时间:2020-12-1714:33

*@Author作者姓名:Liux

*@Version1.0

*@CopyrightCopyrightby

*@Direction类说明

*/

publicclassHttpRequestLogimplementsSerializable{

publicfinalstaticStringcollectName="guides";

privateStringurl;

privateStringhttpMethod;

privateStringclassName;

privateStringmethodName;

privateStringip;

privateStringrequestParam;

privateDatenowTime=TimeHelper.getCurrentDate();

....getset省略

}

packagecom.zhx.guides.assistant.web.aspect;

importcom.alibaba.fastjson.JSONObject;

importcom.zhx.guides.assistant.dto.HttpRequestLog;

importorg.aspectj.lang.JoinPoint;

importorg.aspectj.lang.ProceedingJoinPoint;

importorg.aspectj.lang.annotation.*;

importorg.slf4j.Logger;

importorg.slf4j.LoggerFactory;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.data.mongodb.core.MongoTemplate;

importorg.springframework.stereotype.Component;

importorg.springframework.web.context.request.RequestContextHolder;

importorg.springframework.web.context.request.ServletRequestAttributes;

importjavax.servlet.http.httpervletRequest;

/**

*@ClassWebLogAspect

*@Version1.0

*@Date创建时间:2020-03-0310:05

*@CopyrightCopyrightbycompany

*@Direction类说明

*/

@Aspect

@Component

publicclassWebLogAspect{

@Autowired

privateMongoTemplatemongoTemplate;

privatefinalstaticLoggerlogger=LoggerFactory.getLogger(WebLogAspect.class);

/**以controller包下定义的所有请求为切入点*/

@Pointcut("execution(public*com.zhx.guides.assistant.interfaces.controller..*.*(..))")

publicvoidwebLog(){}

/**

*在切点之前织入

*@paramjoinPoint

*@throwsThrowable

*/

@Before("webLog()")

publicvoiddoBefore(JoinPointjoinPoint)throwsThrowable{

//开始打印请求日志

ServletRequestAttributesattributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();

httpervletRequestrequest=attributes.getRequest();

HttpRequestLoghttpRequestLog=newHttpRequestLog();

httpRequestLog.setUrl(request.getRequestURL().toString());

httpRequestLog.setHttpMethod(request.getMethod());

httpRequestLog.setClassName(joinPoint.getSignature().getDeclaringTypeName());

httpRequestLog.setMethodName(joinPoint.getSignature().getName());

httpRequestLog.setIp(request.getRemoteAddr());

//打印请求相关参数

logger.info("=======================Start======================");

//打印请求url

logger.info("URL:{}",httpRequestLog.getUrl());

//打印Httpmethod

logger.info("HTTPMethod:{}",httpRequestLog.getHttpMethod());

//打印调用controller的全路径以及执行方法

logger.info("ClassMethod:{}.{}",httpRequestLog.getClassName(),httpRequestLog.getMethodName());

//打印请求的IP

logger.info("IP:{}",httpRequestLog.getIp());

//打印请求入参

try{

ObjectrequestParam=joinPoint.getArgs();

httpRequestLog.setRequestParam(JSONObject.toJSONString(requestParam));

logger.info("参数:{}",httpRequestLog.getRequestParam());

}catch(Exceptione){

logger.info("参数打印失败,异常:{}",e.getMessage());

}finally{

httpRequestLog.setClassName(null);

try{mongoTemplate.save(httpRequestLog,HttpRequestLog.collectName);}catch(Exceptione){}

}

}

/**

*在切点之后织入

*@throwsThrowable

*/

@After("webLog()")

publicvoiddoAfter()throwsThrowable{

logger.info("=======================End======================");

}

/**

*环绕

*@paramproceedingJoinPoint

*@return

*@throwsThrowable

*/

@Around("webLog()")

publicObjectdoAround(ProceedingJoinPointproceedingJoinPoint)throwsThrowable{

longstartTime=System.currentTimeMillis();

Objectresult=proceedingJoinPoint.proceed();

//打印出参

logger.info("返回值:{}",JSONObject.toJSONString(result));

//执行耗时

logger.info("耗时:{}ms",System.currentTimeMillis()-startTime);

returnresult;

}

}

packagecom.zhx.guides.assistant.util.object;

importorg.apache.commons.lang.StringUtils;

importjava.util.Date;

/**

*@ClassTimeHelper

*@Version1.0

*@Date创建时间:2018/12/2109:26

*@CopyrightCopyrightby

*@Direction类说明

*/

publicclassTimeHelper{

/**

*当前时间

*@return

*/

publicstaticDategetCurrentDate(){

Calendarcalendar=Calendar.getInstance();

returncalendar.getTime();

}

}

三:看看存储日志的效果

备注:请注意使用的mongodb版本:4.2.1依次配置使用即可

如果你使用的最新版本,有可能发生各种权限不能通过的问题,那么请切换至4.2.1稳定版本,用最新版本有点当小白鼠的感觉。

到此这篇关于DockermongoDB4.2.1安装并收集springboot日志的文章就介绍到这了,更多相关Docker安装mongoDB并收集springboot日志内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!

您可能感兴趣的文章:docker中使用mongodb数据库详解(在局域网访问)基于Docker的MongoDB实现授权访问的方法Springboot项目使用Slf4j将日志保存到本地目录的实现代码springboot配置aop切面日志打印过程解析