ELK用户行为日志获取MongoDB数据
后台开发已经把日志写到了mangoDB里了,然后需要把它们从数据库里都给取出来写成文件,然后导入到ELK。目的很简单,就是将mongodb数据导入es建立相应索引。可以在需要监控MongoDB的数据库日志的服务器上部署logstash或filebeat来抓取日志,也可以把logstash放在别机器.
1 安装logstash-input-mongodb插件
默认现在logstash6.xx版本已经自带这个插件,没有的话我们可以手动安装或下载:
这是插件GitHub地址:https://github.com/phutchins/logstash-input-mongodb
./logstash-plugin install logstash-input-mongodb
此步骤安装比较慢,很有可能失败,翻过墙另说。这里建议替换镜像库为国内的库。
首先需要安装gem命令:
yum -y install gem
查看镜像库地址:
gem sources -l
开始替换为国内的ruby-china:(或https://ruby.taobao.org/)
gem sources --add https://gems.ruby-china.org/ --remove https://rubygems.org/
执行完毕再次执行gem sources -l 检查一下,还需要修改gemfile文件,将文件里的 source "https://rubygems.org" 换成 source "https://gems.ruby-china.org":
sed -i 's#https://rubygems.org#https://gems.ruby-china.org#g' Gemfile
最后重新执行./logstash-plugin install logstash-input-mongodb,就可以顺利安装这个插件了,接下来就是添加logstash配置文件如下:
cat mongo.conf
input { mongodb { uri => 'mongodb://1xx.xx.1xx.xxx:27017/userRecord' placeholder_db_dir => '/opt' placeholder_db_name =>'userRecord' collection => 'userRecord' } } filter { mutate { rename => ["_id", "uid"] } mutate { convert => ["userName","string"] #更改userName字段的类型为string } date { match => ["accessTime", "yyyy-MM-dd HH:mm:ss.SSS"] target => "@timestamp" } } output { file { path => "/var/log/mongons.log" } stdout { codec => json_lines } elasticsearch { user => "elastic" password => "xiange" hosts => ["10.10.16.253:9200"] index => "mongodb_%{+YYYY.MM.dd}" } }
启动Logstash并查看日志:
nohup sh bin/logstash -f conf/mongo.conf & tail -f nohup.out
2 kibana创建索引
创建完索引,最终展示如下:



浙公网安备 33010602011771号