github.com/astaxie/beego@v1.12.3/logs/es/es.go (about) 1 package es 2 3 import ( 4 "context" 5 "encoding/json" 6 "errors" 7 "fmt" 8 "net/url" 9 "strings" 10 "time" 11 12 "github.com/elastic/go-elasticsearch/v6" 13 "github.com/elastic/go-elasticsearch/v6/esapi" 14 15 "github.com/astaxie/beego/logs" 16 ) 17 18 // NewES return a LoggerInterface 19 func NewES() logs.Logger { 20 cw := &esLogger{ 21 Level: logs.LevelDebug, 22 } 23 return cw 24 } 25 26 // esLogger will log msg into ES 27 // before you using this implementation, 28 // please import this package 29 // usually means that you can import this package in your main package 30 // for example, anonymous: 31 // import _ "github.com/astaxie/beego/logs/es" 32 type esLogger struct { 33 *elasticsearch.Client 34 DSN string `json:"dsn"` 35 Level int `json:"level"` 36 } 37 38 // {"dsn":"http://localhost:9200/","level":1} 39 func (el *esLogger) Init(jsonconfig string) error { 40 err := json.Unmarshal([]byte(jsonconfig), el) 41 if err != nil { 42 return err 43 } 44 if el.DSN == "" { 45 return errors.New("empty dsn") 46 } else if u, err := url.Parse(el.DSN); err != nil { 47 return err 48 } else if u.Path == "" { 49 return errors.New("missing prefix") 50 } else { 51 conn, err := elasticsearch.NewClient(elasticsearch.Config{ 52 Addresses: []string{el.DSN}, 53 }) 54 if err != nil { 55 return err 56 } 57 el.Client = conn 58 } 59 return nil 60 } 61 62 // WriteMsg will write the msg and level into es 63 func (el *esLogger) WriteMsg(when time.Time, msg string, level int) error { 64 if level > el.Level { 65 return nil 66 } 67 68 idx := LogDocument{ 69 Timestamp: when.Format(time.RFC3339), 70 Msg: msg, 71 } 72 73 body, err := json.Marshal(idx) 74 if err != nil { 75 return err 76 } 77 req := esapi.IndexRequest{ 78 Index: fmt.Sprintf("%04d.%02d.%02d", when.Year(), when.Month(), when.Day()), 79 DocumentType: "logs", 80 Body: strings.NewReader(string(body)), 81 } 82 _, err = req.Do(context.Background(), el.Client) 83 return err 84 } 85 86 // Destroy is a empty method 87 func (el *esLogger) Destroy() { 88 } 89 90 // Flush is a empty method 91 func (el *esLogger) Flush() { 92 93 } 94 95 type LogDocument struct { 96 Timestamp string `json:"timestamp"` 97 Msg string `json:"msg"` 98 } 99 100 func init() { 101 logs.Register(logs.AdapterEs, NewES) 102 }