mtfosbot/module/es/es.go

43 lines
919 B
Go
Raw Normal View History

2018-10-05 08:36:16 +00:00
package es
import (
2018-10-08 16:11:27 +00:00
"context"
"fmt"
2018-10-09 17:18:52 +00:00
"time"
2018-10-08 16:11:27 +00:00
"git.trj.tw/golang/mtfosbot/module/config"
"github.com/olivere/elastic"
2018-10-05 08:36:16 +00:00
)
var client *elastic.Client
2018-10-08 16:11:27 +00:00
// NewClient -
func NewClient() (err error) {
conf := config.GetConf()
client, err = elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(conf.Elasticsearch.Host))
fmt.Println("host ", conf.Elasticsearch.Host)
if err != nil {
fmt.Println(err)
return
}
return
2018-10-05 08:36:16 +00:00
}
2018-10-08 16:11:27 +00:00
// PutLog -
func PutLog(t string, body map[string]interface{}) (err error) {
2018-10-09 17:18:52 +00:00
if client == nil {
return
}
2018-10-08 16:11:27 +00:00
if len(t) == 0 || body == nil {
return
}
conf := config.GetConf()
ctx := context.Background()
2018-10-09 17:23:43 +00:00
body["timestamp"] = time.Now().UnixNano() / 1000000
body["date"] = time.Now().UTC()
2018-10-09 17:40:10 +00:00
nt := time.Now()
2018-10-09 17:47:04 +00:00
idx := fmt.Sprintf("%v-%v-%v-%v", conf.Elasticsearch.Index, nt.Year(), int(nt.Month()), nt.Day())
2018-10-09 17:40:10 +00:00
_, err = client.Index().Index(idx).Type(t).BodyJson(body).Do(ctx)
2018-10-08 16:11:27 +00:00
return
}