1
0
mirror of https://github.com/astaxie/beego.git synced 2025-06-30 06:40:18 +00:00

Custom formatting opts implementation

This commit is contained in:
IamCathal
2020-08-28 18:18:28 +01:00
parent 2b39ff7837
commit 8178f035a0
8 changed files with 125 additions and 87 deletions

View File

@ -12,6 +12,7 @@ import (
"github.com/elastic/go-elasticsearch/v6"
"github.com/elastic/go-elasticsearch/v6/esapi"
"github.com/astaxie/beego/pkg/common"
"github.com/astaxie/beego/pkg/logs"
)
@ -31,10 +32,9 @@ func NewES() logs.Logger {
// import _ "github.com/astaxie/beego/logs/es"
type esLogger struct {
*elasticsearch.Client
DSN string `json:"dsn"`
Level int `json:"level"`
UseCustomFormatter bool
CustomFormatter func(*logs.LogMsg) string
DSN string `json:"dsn"`
Level int `json:"level"`
customFormatter func(*logs.LogMsg) string
}
func (el *esLogger) Format(lm *logs.LogMsg) string {
@ -42,15 +42,19 @@ func (el *esLogger) Format(lm *logs.LogMsg) string {
}
// {"dsn":"http://localhost:9200/","level":1}
func (el *esLogger) Init(jsonconfig string, LogFormatter ...func(*logs.LogMsg) string) error {
for _, elem := range LogFormatter {
if elem != nil {
el.UseCustomFormatter = true
el.CustomFormatter = elem
func (el *esLogger) Init(jsonConfig string, opts ...common.SimpleKV) error {
for _, elem := range opts {
if elem.Key == "formatter" {
formatter, err := logs.GetFormatter(elem)
if err != nil {
return err
}
el.customFormatter = formatter
}
}
err := json.Unmarshal([]byte(jsonconfig), el)
err := json.Unmarshal([]byte(jsonConfig), el)
if err != nil {
return err
}
@ -79,8 +83,8 @@ func (el *esLogger) WriteMsg(lm *logs.LogMsg) error {
}
msg := ""
if el.UseCustomFormatter {
msg = el.CustomFormatter(lm)
if el.customFormatter != nil {
msg = el.customFormatter(lm)
} else {
msg = el.Format(lm)
}