mtfosbot/module/es/es.go

47 lines
1.0 KiB
Go
Raw Permalink 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()
2019-05-28 03:17:22 +00:00
client, err = elastic.NewClient(
elastic.SetSniff(false),
elastic.SetURL(conf.Elasticsearch.Host),
elastic.SetBasicAuth(conf.Elasticsearch.Username, conf.Elasticsearch.Password),
)
2018-10-08 16:11:27 +00:00
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 -
2019-05-28 03:17:22 +00:00
func PutLog(logType string, body map[string]interface{}) (err error) {
2018-10-09 17:18:52 +00:00
if client == nil {
return
}
2019-05-28 03:17:22 +00:00
if len(logType) == 0 || body == nil {
2018-10-08 16:11:27 +00:00
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())
2019-05-28 03:17:22 +00:00
_, err = client.Index().Index(idx).Type(logType).BodyJson(body).Do(ctx)
2018-10-08 16:11:27 +00:00
return
}