Beats:使用 Filebeat 将 golang 应用程序记录到 Elasticsearch

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

毫无疑问,日志记录是任何应用程序最重要的方面之一。 当事情出错时(而且确实会出错),我们需要知道发生了什么。 为了实现这一目标,我们可以设置 Filebeat 从我们的 golang 应用程序收集日志,然后将它们发送到 Elasticsearch。 最后,使用 Kibana 我们可以可视化这些日志并对它们执行复杂的查询。

安装

如果你还没有安装好自己的 Elasticsearch 及 Kibana,请参考之前文章:

我们还需要下载 Filebeat,并进行相应的安装。在本次的展示中,我将使用最新的 Elastic Stack 8.9.0 来进行展示,但是它也适用于其它的 Elastic Stack 8.x 的安装。当然当前的使用的这种方法也适合 7.x de golang 日志记录,只是我们需要做相应的修改。 针对 7.x 的安装,请参考我的另外一篇文章 "Beats:使用 Elastic Stack 记录 Golang 应用日志"。

创建 golang 应用

我们在当前的应用的根目录下创建如下的一个 go.mod 文件:

go.mod

javascript 复制代码
1.  module logging

3.  require go.elastic.co/ecszap master
markdown 复制代码
1.  $ pwd
2.  /Users/liuxg/go/logging
3.  $ ls
4.  go.mod

我们可以使用如下的命令来下载模块:

go 复制代码
1.  go env -w GO111MODULE=on
2.  go mod download
3.  go mod tidy

我们需要做如下的配置:

css 复制代码
1.  encoderConfig := ecszap.NewDefaultEncoderConfig()
2.  core := ecszap.NewCore(encoderConfig, os.Stdout, zap.DebugLevel)
3.  logger := zap.New(core, zap.AddCaller())

你可以自定义 ECS 记录器。 例如:

markdown 复制代码
1.  encoderConfig := ecszap.EncoderConfig{
2.    EncodeName: customNameEncoder,
3.    EncodeLevel: zapcore.CapitalLevelEncoder,
4.    EncodeDuration: zapcore.MillisDurationEncoder,
5.    EncodeCaller: ecszap.FullCallerEncoder,
6.  }
7.  core := ecszap.NewCore(encoderConfig, os.Stdout, zap.DebugLevel)
8.  logger := zap.New(core, zap.AddCaller())

详细例子

在根目录下创建如下的 app.go 文件:

app.go

markdown 复制代码
1.  package main

3.  import (
4.  	"errors"
5.  	"math/rand"
6.  	"os"
7.  	"time"

9.  	"go.elastic.co/ecszap"
10.  	"go.uber.org/zap"
11.  )

13.  func main() {
14.  	encoderConfig := ecszap.NewDefaultEncoderConfig()
15.  	core := ecszap.NewCore(encoderConfig, os.Stdout, zap.DebugLevel)
16.  	logger := zap.New(core, zap.AddCaller())
17.  	logger = logger.With(zap.String("app", "myapp")).With(zap.String("environment", "psm"))
18.  	count := 0

20.  	for {
21.  		if rand.Float32() > 0.8 {
22.  			logger.Error("oops...something is wrong",
23.  				zap.Int("count", count),
24.  				zap.Error(errors.New("error details")))
25.  		} else {
26.  			logger.Info("everything is fine",
27.  				zap.Int("count", count))
28.  		}
29.  		count++
30.  		time.Sleep(time.Second * 2)
31.  	}
32.  }

我们可以以如下的方式来运行上面的代码:

go 复制代码
go run app.go > a.json

在当前的根目录下,我们可以看见一个叫做 a.json 的文件:

从输出的内容中,我们可以看到 a.json 的文本是一个 JSON 格式的输出。我们在下面来展示如何收集这个日志的信息。

使用 Filebeat 来采集日志并传入到 Elasticsearch 中

我们安装好自己的 FIlebeat,并配置 filebeat.yml 文件:

filebeat.yml

yaml 复制代码
1.  filebeat.inputs:

3.  # Each - is an input. Most options can be set at the input level, so
4.  # you can use different inputs for various configurations.
5.  # Below are the input specific configurations.

7.  # filestream is an input for collecting log messages from files.
8.  - type: log

10.    # Unique ID among all inputs, an ID is required.
11.    id: my-filestream-id

13.    # Change to true to enable this input configuration.
14.    enabled: true

16.    # Paths that should be crawled and fetched. Glob based paths.
17.    paths:
18.      - /Users/liuxg/go/logging/a.json
19.      #- c:\programdata\elasticsearch\logs\*
20.    parsers:
21.      - ndjson:
22.        overwrite_keys: true 
23.        add_error_key: true 
24.        expand_keys: true 

我们需要配置如下的部分:

markdown 复制代码
1.  output.elasticsearch:
2.    # Array of hosts to connect to.
3.    hosts: ["https://localhost:9200"]

5.    # Protocol - either `http` (default) or `https`.
6.    # protocol: "https"

8.    # Authentication credentials - either API key or username/password.
9.    #api_key: "id:api_key"
10.    username: "elastic"
11.    password: "p1k6cT4a4bF+pFYf37Xx"
12.    ssl.certificate_authorities: ["/Users/liuxg/elastic/elasticsearch-8.9.0/config/certs/http_ca.crt"]

在上面,我们需根据自己的 Elasticsearch 的配置来填入上面的用户名及密码。我们需要根据自己的证书的位置来配置证书。我们使用如下的命令来查看配置是否有语法错误:

bash 复制代码
1.  $ pwd
2.  /Users/liuxg/elastic/filebeat-8.9.0-darwin-aarch64
3.  $ ./filebeat test config
4.  Config OK

上面显示我们的配置是没有任何问题的。我们可以使用如下的命令来查看 output 的配置是否成功:

markdown 复制代码
1.  $ ./filebeat test output
2.  elasticsearch: https://localhost:9200...
3.    parse url... OK
4.    connection...
5.      parse host... OK
6.      dns lookup... OK
7.      addresses: 127.0.0.1
8.      dial up... OK
9.    TLS...
10.      security: server's certificate chain verification is enabled
11.      handshake... OK
12.      TLS version: TLSv1.3
13.      dial up... OK
14.    talk to server... OK
15.    version: 8.9.0

上面显示我们的 Elasticsearch 的配置是成功的。

我们可以使用如下的命令来摄入数据:

bash 复制代码
./filebeat -e

到 Kibana 中进行查看

我们可以在 Kibana 中来查看我们收集到的日志信息:

从上面的显示中,可以看出来已经成功地收集了日志信息。当然,我们也可以针对日志进行搜索:

相关推荐
一次旅行15 小时前
【效率秘籍】Shell 函数+别名组合拳,让 80% 的重复命令变 1 个字母
大数据·elasticsearch·搜索引擎
暖和_白开水15 小时前
数据分析agent(九):es_client_manager.py 和分词器ik_max_word问题
elasticsearch·数据分析·c#
码农学院15 小时前
Elasticsearch构建汽车零配件智能搜索与匹配系统
大数据·elasticsearch·汽车
Elastic 中国社区官方博客1 天前
不到 5 分钟完成本地部署:Jina embedding 模型现已支持本地部署
大数据·人工智能·elasticsearch·搜索引擎·embedding·jina
二进制流水搬运工1 天前
入职第一天拉了23个仓库,我写了个脚本解放双手
大数据·elasticsearch·搜索引擎
Elasticsearch1 天前
在不到一小时内将 Datadog Kubernetes 仪表板迁移到 Elastic Observability
elasticsearch
.柒宇.1 天前
Elasticsearch 核心概念与系统架构详解
elasticsearch·系统架构
风行無痕2 天前
单机Elasticsearch 8.19.18安全升级到9.4.3的过程
大数据·elasticsearch·搜索引擎
Elastic 中国社区官方博客2 天前
使用重新设计的 AutoOps 更快地进行 Elasticsearch 问题排查
大数据·运维·前端·人工智能·elasticsearch·搜索引擎·全文检索
阿拉雷️2 天前
【搜索实战】Spring Boot 3.3 + AI Agent × Elasticsearch:让AI自动优化搜索策略,查询速度从2秒压到50毫秒
人工智能·spring boot·elasticsearch