diff options
author | Cliff Lin <cliff.lin@cobinhood.com> | 2019-03-18 18:16:20 +0800 |
---|---|---|
committer | Cliff Lin <cliff.lin@cobinhood.com> | 2019-03-18 18:16:20 +0800 |
commit | db287597a5058ac8a789276d4c13d200732c35f3 (patch) | |
tree | 20ffba69db287c8ccb069f7a4968ada34c9a9bda /log | |
parent | be5da8862281a48c50d7ce89bf35cc6580dca0f7 (diff) | |
download | dexon-cliff-log.tar.gz dexon-cliff-log.tar.zst dexon-cliff-log.zip |
log: add stackdriver handlercliff-log
Diffstat (limited to 'log')
-rw-r--r-- | log/handler_stackdriver.go | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/log/handler_stackdriver.go b/log/handler_stackdriver.go new file mode 100644 index 000000000..68e8b32b2 --- /dev/null +++ b/log/handler_stackdriver.go @@ -0,0 +1,87 @@ +package log + +import ( + "encoding/json" + "fmt" + + "cloud.google.com/go/logging" + "golang.org/x/net/context" +) + +// LabelMap defines stackdriver labels struct. +type LabelMap map[string]string + +// LogMsg defines json object of log message. +type LogMsg struct { + Msg string `json:"msg"` + Label LabelMap `json:"label"` +} + +// StackdriverHandler is a log handler of stackdrvier. +type StackdriverHandler struct { + client *logging.Client + logger *logging.Logger +} + +// NewStackDriverHandler returns a new handler. +func NewStackDriverHandler(projectID, logName string) (*StackdriverHandler, error) { + client, err := logging.NewClient(context.Background(), projectID) + if err != nil { + return nil, fmt.Errorf("Failed to create client: %v", err) + } + return &StackdriverHandler{ + client: client, + logger: client.Logger(logName), + OmitEmpty: true, + }, nil +} + +// Log send to stackdriver. +func (h *StackdriverHandler) Log(r *Record) error { + e := logging.Entry{ + Payload: r.Msg, + Timestamp: r.Time, + Severity: asSeverity(r.Lvl), + } + e.Labels = LabelMap{"tag": "test"} + parseLabel(&e) + h.logger.Log(e) +} + +func parseLabel(e *logging.Entry) { + var log LogMsg + payload := []byte(e.Payload.(string)) + err := json.Unmarshal(payload, &log) + if err != nil { + fmt.Println("%v", err) + return + } + + e.Payload = log.Msg + e.Labels = log.Label +} + +func asSeverity(l Lvl) logging.Severity { + switch l { + case LvlDebug: + return logging.Debug + case LvlCrit: + return logging.Emergency + case LvlError: + return logging.Error + case LvlInfo: + return logging.Info + case LvlWarn: + return logging.Warning + default: + return logging.Notice + } +} + +// Close is delegated to the client (if any) +func (h *StackdriverHandler) Close() error { + if h.client == nil { + return nil + } + return h.client.Close() +} |