mirror of
https://github.com/astaxie/beego.git
synced 2025-06-12 20:00:39 +00:00
Fix ES client
This commit is contained in:
@ -1,14 +1,17 @@
|
||||
package es
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/OwnLocal/goes"
|
||||
"github.com/elastic/go-elasticsearch/v6"
|
||||
"github.com/elastic/go-elasticsearch/v6/esapi"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
)
|
||||
|
||||
@ -21,7 +24,7 @@ func NewES() logs.Logger {
|
||||
}
|
||||
|
||||
type esLogger struct {
|
||||
*goes.Client
|
||||
*elasticsearch.Client
|
||||
DSN string `json:"dsn"`
|
||||
Level int `json:"level"`
|
||||
}
|
||||
@ -38,10 +41,13 @@ func (el *esLogger) Init(jsonconfig string) error {
|
||||
return err
|
||||
} else if u.Path == "" {
|
||||
return errors.New("missing prefix")
|
||||
} else if host, port, err := net.SplitHostPort(u.Host); err != nil {
|
||||
return err
|
||||
} else {
|
||||
conn := goes.NewClient(host, port)
|
||||
conn, err := elasticsearch.NewClient(elasticsearch.Config{
|
||||
Addresses: []string{u.Host},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
el.Client = conn
|
||||
}
|
||||
return nil
|
||||
@ -53,21 +59,26 @@ func (el *esLogger) WriteMsg(when time.Time, msg string, level int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
vals := make(map[string]interface{})
|
||||
vals["@timestamp"] = when.Format(time.RFC3339)
|
||||
vals["@msg"] = msg
|
||||
d := goes.Document{
|
||||
Index: fmt.Sprintf("%04d.%02d.%02d", when.Year(), when.Month(), when.Day()),
|
||||
Type: "logs",
|
||||
Fields: vals,
|
||||
idx := LogDocument{
|
||||
timestamp: when.Format(time.RFC3339),
|
||||
msg: msg,
|
||||
}
|
||||
_, err := el.Index(d, nil)
|
||||
|
||||
body, err := json.Marshal(idx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req := esapi.IndexRequest{
|
||||
Index: fmt.Sprintf("%04d.%02d.%02d", when.Year(), when.Month(), when.Day()),
|
||||
DocumentType: "logs",
|
||||
Body: strings.NewReader(string(body)),
|
||||
}
|
||||
_, err = req.Do(context.Background(), el.Client)
|
||||
return err
|
||||
}
|
||||
|
||||
// Destroy is a empty method
|
||||
func (el *esLogger) Destroy() {
|
||||
|
||||
}
|
||||
|
||||
// Flush is a empty method
|
||||
@ -75,7 +86,11 @@ func (el *esLogger) Flush() {
|
||||
|
||||
}
|
||||
|
||||
type LogDocument struct {
|
||||
timestamp string
|
||||
msg string
|
||||
}
|
||||
|
||||
func init() {
|
||||
logs.Register(logs.AdapterEs, NewES)
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user