You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kratos/pkg/log/handler.go

119 lines
2.4 KiB

package log
import (
"context"
6 years ago
"time"
pkgerr "github.com/pkg/errors"
)
const (
6 years ago
_timeFormat = "2006-01-02T15:04:05.999999"
// log level defined in level.go.
_levelValue = "level_value"
// log level name: INFO, WARN...
_level = "level"
// log time.
_time = "time"
// request path.
// _title = "title"
6 years ago
// log file.
_source = "source"
// common log filed.
_log = "log"
6 years ago
// app name.
_appID = "app_id"
// container ID.
_instanceID = "instance_id"
// uniq ID from trace.
_tid = "traceid"
// request time.
// _ts = "ts"
6 years ago
// requester.
_caller = "caller"
// container environment: prod, pre, uat, fat.
_deplyEnv = "env"
// container area.
_zone = "zone"
// mirror flag
_mirror = "mirror"
// color.
_color = "color"
// env_color
_envColor = "env_color"
6 years ago
// cluster.
_cluster = "cluster"
)
// Handler is used to handle log events, outputting them to
// stdio or sending them to remote services. See the "handlers"
// directory for implementations.
//
// It is left up to Handlers to implement thread-safety.
type Handler interface {
// Log handle log
// variadic D is k-v struct represent log content
Log(context.Context, Level, ...D)
// SetFormat set render format on log output
// see StdoutHandler.SetFormat for detail
SetFormat(string)
// Close handler
Close() error
}
6 years ago
func newHandlers(filters []string, handlers ...Handler) *Handlers {
set := make(map[string]struct{})
for _, k := range filters {
set[k] = struct{}{}
}
return &Handlers{filters: set, handlers: handlers}
}
// Handlers a bundle for hander with filter function.
type Handlers struct {
filters map[string]struct{}
handlers []Handler
}
// Log handlers logging.
func (hs Handlers) Log(ctx context.Context, lv Level, d ...D) {
hasSource := false
6 years ago
for i := range d {
if _, ok := hs.filters[d[i].Key]; ok {
d[i].Value = "***"
}
if d[i].Key == _source {
hasSource = true
6 years ago
}
}
if !hasSource {
fn := funcName(3)
errIncr(lv, fn)
d = append(d, KVString(_source, fn))
6 years ago
}
d = append(d, KV(_time, time.Now()), KVInt64(_levelValue, int64(lv)), KVString(_level, lv.String()))
6 years ago
for _, h := range hs.handlers {
h.Log(ctx, lv, d...)
}
}
// Close close resource.
func (hs Handlers) Close() (err error) {
6 years ago
for _, h := range hs.handlers {
if e := h.Close(); e != nil {
err = pkgerr.WithStack(e)
}
}
return
}
// SetFormat .
func (hs Handlers) SetFormat(format string) {
6 years ago
for _, h := range hs.handlers {
h.SetFormat(format)
}
}