Skip to content
Oliver Eilhard edited this page Feb 13, 2018 · 8 revisions

Elastic has three kinds of logs:

First, there's the error log. It will contain critical messages, e.g. nodes leaving or joining the cluster or connections that fail. You can set the error log with elastic.SetErrorLog(elastic.Logger). It is nil by default, i.e. Elastic is silent.

Second, there's the info log. It will contain informational messages, e.g. request and response time. You can set the info log with elastic.SetInfoLog(elastic.Logger). It is nil by default, i.e. Elastic is silent.

Third, there's the trace log. It is suitable for debugging, e.g. dump the Elasticsearch HTTP response. It is also nil by default. You can specify a trace log with elastic.SetTraceLog(elastic.Logger).

A logger must implement the single-function interface Logger, which only asks for a function with this signature: Printf(format string, v ...interface{}). As *log.Logger from the standard library implements this method, it can be used. You can write simple wrappers to plug into your logging solution of choice (see below for an example).

All three kinds of logs can be specified via an option to NewClient. Here's an example where the error log is set to os.Stderr and info log is set to os.Stdout:

import (
  "log"
  "os"
  ...
)

client, err := elastic.NewClient(
  elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC ", log.LstdFlags)),
  elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags)))

If you want to log to a file, use something like this:

file, err := os.OpenFile("elastic.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664)
if err != nil {
  panic(err)
}
client, err := elastic.NewClient(
  elastic.SetErrorLog(log.New(file, "ELASTIC ", log.LstdFlags)))

You can log to any logging solution out there by providing a wrapper. Here's an example for github.com/go-kit/kit/log.

import "github.com/go-kit/kit/log"

type wrapKitLogger struct {
	log.Logger
}

func (logger wrapKitLogger) Printf(format string, vars ...interface{}) {
	logger.Log("msg", fmt.Sprintf(format, vars...))
}

...

logger := log.NewLogfmtLogger(os.Stdout)
wrappedLogger := &wrapKitLogger{logger}
client, err := elastic.NewClient(elastic.SetErrorLog(wrappedLogger))
client, err := elastic.NewClient(
  elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC ", log.LstdFlags)),
  elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags))),
elastic.SetTraceLog(log.New(os.Stderr, "[[ELASTIC]]", 0))))

will enable data outputs.

Clone this wiki locally