0

logrus用来记录我的 golang 应用程序。但是,我还想将它与 Elastic Search 集成,这样当我创建 logrus 日志条目时,所有日志也会刷新到 Elastic Search。目前所有日志都在一个文件中创建,如下面的代码片段所示。我如何与弹性搜索集成?

type LoggerConfig struct {
    Filename string `validate:regexp=.log$`
    AppName  string `validate:regexp=^[a-zA-Z]$`
}  

type AppLogger struct {
    Err    error
    Logger logrus.Entry
}

func Logger(loggerConfig LoggerConfig) AppLogger {
    response := new(AppLogger)
    // validate the schema of the logger_config
    if errs := validator.Validate(loggerConfig); errs != nil {
        response.Err = errs
        // this sets up the error on the the response struct
    }

    logrus.SetFormatter(&logrus.JSONFormatter{})
    f, err := os.OpenFile(loggerConfig.Filename, os.O_WRONLY|os.O_CREATE, 0755)
    if err != nil {
        response.Err = err
    }
    multipleWriter := io.MultiWriter(os.Stdout, f)
    logrus.SetOutput(multipleWriter)

    contextLogger := logrus.WithFields(logrus.Fields{
        "app": loggerConfig.AppName,
    })


    //logrus.AddHook(hook)
    response.Logger = *contextLogger

    //response.Logger.Info("adele")
    return *response

}

我试过elogrus添加一个钩子,但我不知道如何使用它。这是尝试创建弹性搜索客户端的方法。我如何将它与 logrus 实例集成?

func prepareElasticSearchClient() *elastic.Client {
    indexName := "my-server"

    client, _ := elastic.NewClientFromConfig(&config.Config{
        URL:      os.Getenv("ELASTIC_SEARCH_URL_LOGS") + ":" + os.Getenv("ELASTIC_SEARCH_PORT_LOGS"),
        Index:    indexName,
        Username: os.Getenv("ELASTIC_SEARCH_USERNAME_LOGS"),
        Password: os.Getenv("ELASTIC_SEARCH_PASSWORD_LOGS"),
    })

    return client
}

早些时候,我使用过诸如Winston设置弹性搜索日志记录非常容易的模块,但不知何故,我发现很少有关于如何将 Golang 日志记录与弹性搜索集成的 golang 文档

4

1 回答 1

1

elogrus首先创建 Elastic 客户端并在elogrus使用elogrus.NewAsyncElasticHook(). Hook 只是包装了向 Elastic 发送消息。然后将此钩子添加到logrus log. 每次您使用log它记录消息时,都会触发您的钩子并将消息(如果日志级别过滤器通过)发送到 Elastic。

log := logrus.New()
client, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"))
// ... handle err
hook, err := elogrus.NewAsyncElasticHook(client, "localhost", logrus.DebugLevel, "testlog")
// ... handle err
log.Hooks.Add(hook)

的签名在NewAsyncElasticHook哪里(client *elastic.Client, host string, level logrus.Level, index string)

  • clientElastic.Client是在使用之前获得的指向您的指针elastic
  • host是表示您从哪个主机发送日志跟踪的字符串(它是一个字符串 - 正在运行日志程序的主机的主机名)
  • level是您希望发送消息的最大 logrus 日志级别(例如,如果您想在本地查看 DEBUG 消息但只发送 ERROR 及以下消息到 Elastic)
  • index是您要从log中添加消息的 Elastic Search 索引的名称

从这里您可以log正常使用logrus,所有消息都将传递给 Elastic。

问题的另一部分有点棘手,并且植根于(不仅是)Golangelastic客户端节点嗅探行为。我们在聊天中对其进行了调试,并将摘要发布为我对 OP 的另一个问题的回答:无法连接到弹性搜索:未找到活动连接:没有可用的 Elasticsearch 节点

于 2020-04-27T05:45:28.407 回答