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.

56 lines
1.1 KiB

2 years ago
package log
import (
"context"
"runtime"
"strconv"
"strings"
"time"
)
var (
DefaultCaller = Caller(4)
DefaultTimestamp = Timestamp(time.RFC3339)
)
type Valuer func(ctx context.Context) any
func Value(ctx context.Context, v any) any {
if v, ok := v.(Valuer); ok {
return v(ctx)
}
return v
}
func Caller(depth int) Valuer {
return func(ctx context.Context) any {
_, file, line, _ := runtime.Caller(depth)
idx := strings.LastIndexByte(file, '/')
if idx == -1 {
return file[idx+1:] + ":" + strconv.Itoa(line)
}
idx = strings.LastIndexByte(file[:idx], '/')
return file[idx+1:] + ":" + strconv.Itoa(line)
}
}
func Timestamp(layout string) Valuer {
return func(ctx context.Context) any {
return time.Now().Format(layout)
}
}
func bindValues(ctx context.Context, keyvals []any) {
for i := 1; i < len(keyvals); i += 2 {
if v, ok := keyvals[i].(Valuer); ok {
keyvals[i] = v(ctx)
}
}
}
func containsValuer(keyvals []any) bool {
for i := 1; i < len(keyvals); i += 2 {
if _, ok := keyvals[i].(Valuer); ok {
return true
}
}
return false
}