Documentation
¶
Overview ¶
Example ¶
package main
import (
"log"
"log/slog"
slogelastic "github.com/nicus101/slog-elastic"
)
func main() {
// initialize by config
slogEsCfg := slogelastic.Config{
Address: "https://example.com",
Index: "some-log-index",
User: "john",
Pass: "secret",
MinLevel: slog.LevelDebug,
}
// load from .env or enviroment ES_LOG_xxx
err := slogEsCfg.LoadFromEnv()
if err != nil {
log.Fatal(err)
}
// connecting to ElasticSearch and selecting index
err = slogEsCfg.ConnectEsLog()
if err != nil {
log.Fatal(err)
}
// or use arleady established connection
slogEsCfg.ESIndex = slogelastic.AlreadyConnected()
// finalize configuration and build slog.Handler
esHandler := slogEsCfg.NewElasticHandler()
// To see output in terminal, we recomend slogmulti.Fanout from Samber
slog.SetDefault(slog.New(esHandler))
// now we can use persistent logging in rest of application
slog.Info("Registered banana", "bannanaId", 42)
slog.Warn("Invalid monkeyId", "monkeyId", "mojo")
slog.Error("BannanaDB connection failed", "error", "unknown protocol banana://")
}
Output: {"bannanaId":42,"level":"INFO","message":"Registered banana","time":"0001-01-01T00:00:00Z"} {"level":"WARN","message":"Invalid monkeyId","monkeyId":"mojo","time":"0001-01-01T00:00:00Z"} {"error":"unknown protocol banana://","level":"ERROR","message":"BannanaDB connection failed","time":"0001-01-01T00:00:00Z"}
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
Address string `env:"ES_LOG_ADDRESS"`
Index string `env:"ES_LOG_INDEX"`
User string `env:"ES_LOG_USER"`
Pass string `env:"ES_LOG_PASS"`
ESIndex *index.Index
MinLevel slog.Level
ContextFuncs []ContextAttrFunc
ErrorHandler ErrorHandlerFunc
}
func (*Config) ConnectEsLog ¶
ConnectEsLog establishes a connection to Elasticsearch using the configured credentials and initializes the ESIndex client for the specified index. It returns an error if the connection cannot be established.
func (*Config) LoadFromEnv ¶
LoadFromEnv loads configuration from environment variables, optionally reading from a .env file if present. It validates required fields and returns an error if any required field is missing or if there are issues loading the environment variables. The function will not return an error if the .env file is missing, but will return errors for other file-related issues.
func (Config) NewElasticHandler ¶
NewElasticHandler creates a new Handler with the given configuration and options
type ErrorHandlerFunc ¶
type ErrorHandlerFunc func(error)
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
func (*Handler) Handle ¶
Handle processes a log record, converting it to a document and sending it to Elasticsearch