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

2023年 8月 14日 20.5k 0

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

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

安装

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

  • 如何在 Linux,MacOS 及 Windows 上进行安装 Elasticsearch

  • Kibana:如何在 Linux,MacOS 及 Windows 上安装 Elastic 栈中的 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



1.  module logging

3.  require go.elastic.co/ecszap master




1.  $ pwd
2.  /Users/liuxg/go/logging
3.  $ ls
4.  go.mod


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



1.  go env -w GO111MODULE=on
2.  go mod download
3.  go mod tidy


我们需要做如下的配置:



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


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



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



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 run app.go > a.json

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

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

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

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

filebeat.yml

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:programdataelasticsearchlogs*
20.    parsers:
21.      - ndjson:
22.        overwrite_keys: true 
23.        add_error_key: true 
24.        expand_keys: true 

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



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 的配置来填入上面的用户名及密码。我们需要根据自己的证书的位置来配置证书。我们使用如下的命令来查看配置是否有语法错误:



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


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



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 的配置是成功的。

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

./filebeat -e

到 Kibana 中进行查看

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

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

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论