File size: 2,001 Bytes
7e312e3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | package reqlog
import (
"context"
"strings"
"sync"
)
type ctxKey struct{}
// Record 是中间件挂在 request context 上的可变记录,业务代码可补充字段。
type Record struct {
mu sync.Mutex
e Entry
}
func WithRecord(ctx context.Context, rec *Record) context.Context {
return context.WithValue(ctx, ctxKey{}, rec)
}
func FromContext(ctx context.Context) *Record {
if ctx == nil {
return nil
}
rec, _ := ctx.Value(ctxKey{}).(*Record)
return rec
}
func (r *Record) set(fn func(*Entry)) {
if r == nil {
return
}
r.mu.Lock()
fn(&r.e)
r.mu.Unlock()
}
// Snapshot 返回当前记录的副本。
func (r *Record) Snapshot() Entry {
if r == nil {
return Entry{}
}
r.mu.Lock()
defer r.mu.Unlock()
return r.e
}
func SetAPIKey(ctx context.Context, name, masked string) {
FromContext(ctx).set(func(e *Entry) {
if name != "" {
e.APIKeyName = name
}
if masked != "" {
e.APIKey = masked
}
})
}
func SetAccount(ctx context.Context, account string) {
FromContext(ctx).set(func(e *Entry) { e.Account = account })
}
func SetModel(ctx context.Context, model string) {
FromContext(ctx).set(func(e *Entry) { e.Model = model })
}
func SetStream(ctx context.Context, stream bool) {
FromContext(ctx).set(func(e *Entry) { e.Stream = stream })
}
func SetErrorCode(ctx context.Context, code, message string) {
FromContext(ctx).set(func(e *Entry) {
if code != "" {
e.ErrorCode = code
}
if message != "" {
e.Error = truncate(message, 500)
}
})
}
func SetUpstream(ctx context.Context, detail string) {
FromContext(ctx).set(func(e *Entry) { e.Upstream = truncate(detail, 500) })
}
func truncate(s string, max int) string {
s = strings.TrimSpace(s)
if len(s) <= max {
return s
}
return s[:max] + "..."
}
// MaskKey 只保留密钥前 6 位,避免日志泄露完整凭证。
func MaskKey(key string) string {
key = strings.TrimSpace(key)
if key == "" {
return ""
}
if len(key) <= 6 {
return "***"
}
return key[:6] + "***"
}
|