Docker mongoDB 4.2.1 安装并收集springboot日志的步骤详解
一: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 此处我们设置为非登录可见 新docker人请参考前期文章知晓参数,启动完成后。咱们开始整账户
这个是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 此处我们设置为非登录可见 新docker人请参考前期文章知晓参数,启动完成后。咱们开始整账户
第三步:mongodb 配置好用户信息
为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" } ])
为MongoDb创建账户信息,如果你不需要验证可以不跑这一段,但是生产环境可不要这么干 # 连接至docker中的命令操作界面 [root@izwz99z5o9dc90keftqhlrz ~]# docker exec -it mongo mongo admin # 创建一个名为 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 数据库,再添加用户,否则不知道你添加到哪里去了 > use guides #或者直接创建时给所有者权限 > 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添加配置
org.springframework.boot spring-boot-starter-mongodb
第二步:application.yml 配置好连接
#告诉Spring Boot应该在何处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切片日志获取
package com.zhx.guides.assistant.dto; import com.zhx.guides.assistant.util.object.TimeHelper; import java.io.Serializable; import java.util.Date; /** * @Date 创建时间: 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 创建时间: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 包下定义的所有请求为切入点 */ @Pointcut("execution(public * com.zhx.guides.assistant.interfaces.controller..*.*(..))") public void webLog() {} /** * 在切点之前织入 * @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() ); // 打印请求相关参数 logger.info("======================= Start ======================"); // 打印请求 url logger.info("URL : {}", httpRequestLog.getUrl() ); // 打印 Http method logger.info("HTTP Method : {}", httpRequestLog.getHttpMethod() ); // 打印调用 controller 的全路径以及执行方法 logger.info("Class Method : {}.{}", httpRequestLog.getClassName() , httpRequestLog.getMethodName()); // 打印请求的 IP logger.info("IP : {}", httpRequestLog.getIp() ); // 打印请求入参 try { Object requestParam = joinPoint.getArgs(); httpRequestLog.setRequestParam( JSONObject.toJSONString(requestParam) ); logger.info("参数 : {}", httpRequestLog.getRequestParam() ); }catch (Exception e){ logger.info("参数打印失败,异常: {}", e.getMessage() ); }finally { httpRequestLog.setClassName( null ); try{mongoTemplate.save( httpRequestLog , HttpRequestLog.collectName );}catch (Exception e){} } } /** * 在切点之后织入 * @throws Throwable */ @After("webLog()") public void doAfter() throws Throwable { logger.info("======================= End ======================"); } /** * 环绕 * @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)); // 执行耗时 logger.info("耗时 : {} 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 创建时间:2018/12/21 09:26 * @Copyright Copyright by * @Direction 类说明 */ public class TimeHelper { /** *当前时间 * @return */ public static Date getCurrentDate(){ Calendar calendar = Calendar.getInstance(); return calendar.getTime(); } }
三:看看存储日志的效果
备注:请注意使用的mongodb版本:4.2.1 依次配置使用即可
如果你使用的最新版本,有可能发生各种 权限不能通过的问题,那么请切换至4.2.1稳定版本,用最新版本有点当小白鼠的感觉。
到此这篇关于Docker mongoDB 4.2.1 安装并收集springboot日志的文章就介绍到这了,更多相关Docker安装mongoDB并收集springboot日志内容请搜索潘少俊衡以前的文章或继续浏览下面的相关文章希望大家以后多多支持潘少俊衡!
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。
本文地址:/jtjc/Linux/106909.html