抽取 Gin、配置、日志、数据库、Redis 与出站 HTTP 基础能力。 新增统一接入指南,将能力清单和相对链接检查纳入 make verify。 对齐远端 module 路径,修正 Redis 读写超时特殊值映射。 验证:make verify、make race-check 均通过。
This commit is contained in:
commit
b4c3ac622c
55 files changed
+5862
No files matched your search
@@ -0,0 +1,225 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
// OutputConfig 描述本地文件及可选控制台输出,不包含远端采集器。
|
||||
type OutputConfig struct {
|
||||
Name string `json:"name" dc:"日志实例及文件名称"`
|
||||
Path string `json:"path" dc:"日志文件目录"`
|
||||
TimeIntervalType string `json:"time_interval_type" dc:"HOUR、DAY、MONTH 或 YEAR 切割规则"`
|
||||
DivisionChar string `json:"division_char" dc:"日期和文件名之间的分隔符"`
|
||||
LogLevel string `json:"log_level" dc:"最低记录等级"`
|
||||
Console bool `json:"console" dc:"是否同时输出到标准输出"`
|
||||
UseJSON bool `json:"use_json" dc:"是否使用 JSON 编码"`
|
||||
FileLine bool `json:"file_line" dc:"是否记录调用文件行号"`
|
||||
MessageKey string `json:"message_key" dc:"消息字段名"`
|
||||
LevelKey string `json:"level_key" dc:"等级字段名"`
|
||||
TimeKey string `json:"time_key" dc:"时间字段名"`
|
||||
CallerKey string `json:"caller_key" dc:"调用位置字段名"`
|
||||
UseShortFile bool `json:"use_short_file" dc:"是否缩短调用文件路径"`
|
||||
CallerSkip int `json:"caller_skip" dc:"额外跳过的调用栈层数"`
|
||||
MaxAge int64 `json:"max_age" dc:"文件保留秒数,非正值沿用三天"`
|
||||
}
|
||||
|
||||
// output 保存实例与文件句柄,确保退出时真正关闭文件。
|
||||
type output struct {
|
||||
logger *zap.Logger `dc:"本地输出的日志实例"`
|
||||
writer *rotatelogs.RotateLogs `dc:"轮转文件的所属句柄"`
|
||||
}
|
||||
|
||||
var (
|
||||
outputMutex sync.RWMutex
|
||||
outputs = make(map[string]output)
|
||||
missingOutput = zap.NewNop()
|
||||
)
|
||||
|
||||
// Instance 获取已配置的命名日志,未配置时沿用空日志行为。
|
||||
// 入参:name 为入口 YAML 中的日志实例名。
|
||||
// 返回:只供写日志的 Zap 实例,调用方不得关闭。
|
||||
func Instance(name string) *zap.Logger {
|
||||
var (
|
||||
item output
|
||||
)
|
||||
var (
|
||||
exists bool
|
||||
)
|
||||
outputMutex.RLock()
|
||||
item, exists = outputs[name]
|
||||
outputMutex.RUnlock()
|
||||
if !exists {
|
||||
return missingOutput
|
||||
}
|
||||
return item.logger
|
||||
}
|
||||
|
||||
// ConfigureOutput 创建并发布一个本地日志实例,拒绝覆盖活动实例。
|
||||
// 入参:cfg 为已应用入口默认值的输出配置。
|
||||
// 返回:已发布实例;失败返回带内部场景码及原因链的错误,不修改活动实例。
|
||||
func ConfigureOutput(cfg *OutputConfig) (*zap.Logger, error) {
|
||||
var (
|
||||
writer *rotatelogs.RotateLogs
|
||||
)
|
||||
var (
|
||||
err error
|
||||
)
|
||||
var (
|
||||
pattern string
|
||||
)
|
||||
var (
|
||||
interval time.Duration
|
||||
)
|
||||
var (
|
||||
cores []zapcore.Core
|
||||
)
|
||||
var (
|
||||
options []zap.Option
|
||||
)
|
||||
var (
|
||||
level = zapcore.InfoLevel
|
||||
)
|
||||
var (
|
||||
maxAge = int64(3 * 24 * 3600)
|
||||
)
|
||||
var (
|
||||
name, division string
|
||||
)
|
||||
outputMutex.Lock()
|
||||
defer outputMutex.Unlock()
|
||||
if cfg == nil || strings.TrimSpace(cfg.Name) == "" || strings.TrimSpace(cfg.Path) == "" {
|
||||
return nil, outputFailure(CodeOutputConfig, "local log output configuration is incomplete", nil)
|
||||
}
|
||||
if _, exists := outputs[cfg.Name]; exists {
|
||||
return nil, outputFailure(CodeOutputDuplicate, "local log output is already initialized", nil)
|
||||
}
|
||||
if err = os.MkdirAll(cfg.Path, 0755); err != nil {
|
||||
return nil, outputFailure(CodeOutputDirectory, "create local log directory failed", err)
|
||||
}
|
||||
name, division = cfg.Name, cfg.DivisionChar
|
||||
if !strings.Contains(name, ".") {
|
||||
name += ".log"
|
||||
}
|
||||
if division == "" {
|
||||
division = "-"
|
||||
}
|
||||
switch strings.ToUpper(cfg.TimeIntervalType) {
|
||||
case "HOUR":
|
||||
pattern, interval = "%Y"+division+"%m"+division+"%d"+division+"%H", time.Hour
|
||||
case "MONTH":
|
||||
pattern, interval = "%Y"+division+"%m", 30*24*time.Hour
|
||||
case "YEAR":
|
||||
pattern, interval = "%Y", 365*24*time.Hour
|
||||
default:
|
||||
pattern, interval = "%Y"+division+"%m"+division+"%d", 24*time.Hour
|
||||
}
|
||||
if cfg.MaxAge > 0 {
|
||||
maxAge = cfg.MaxAge
|
||||
}
|
||||
if writer, err = rotatelogs.New(filepath.Join(cfg.Path, pattern+division+name), rotatelogs.WithRotationTime(interval), rotatelogs.WithMaxAge(time.Duration(maxAge)*time.Second)); err != nil {
|
||||
return nil, outputFailure(CodeOutputWriter, "create rotating log writer failed", err)
|
||||
}
|
||||
// 保留既有未知等级回落 INFO 的契约。
|
||||
if parsed, parseErr := zapcore.ParseLevel(strings.ToLower(cfg.LogLevel)); parseErr == nil {
|
||||
level = parsed
|
||||
}
|
||||
cores = append(cores, zapcore.NewCore(cfg.encoder(), zapcore.AddSync(writer), level))
|
||||
if cfg.Console {
|
||||
cores = append(cores, zapcore.NewCore(cfg.encoder(), zapcore.Lock(os.Stdout), level))
|
||||
}
|
||||
if cfg.FileLine {
|
||||
options = append(options, zap.AddCaller(), zap.AddCallerSkip(cfg.CallerSkip))
|
||||
}
|
||||
var (
|
||||
instance = zap.New(zapcore.NewTee(cores...), options...)
|
||||
)
|
||||
outputs[cfg.Name] = output{
|
||||
logger: instance,
|
||||
writer: writer,
|
||||
}
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
// encoder 构建当前输出的编码器。
|
||||
// 返回:独立的 JSON 或控制台编码器,不在多个 Core 间共享可变状态。
|
||||
func (cfg *OutputConfig) encoder() zapcore.Encoder {
|
||||
var (
|
||||
encoder = zapcore.EncoderConfig{
|
||||
MessageKey: "message",
|
||||
LevelKey: "level",
|
||||
TimeKey: "time",
|
||||
CallerKey: "file",
|
||||
EncodeLevel: zapcore.CapitalLevelEncoder,
|
||||
EncodeTime: outputTime,
|
||||
EncodeDuration: zapcore.MillisDurationEncoder,
|
||||
EncodeCaller: zapcore.FullCallerEncoder,
|
||||
}
|
||||
)
|
||||
if cfg.MessageKey != "" {
|
||||
encoder.MessageKey = cfg.MessageKey
|
||||
}
|
||||
if cfg.LevelKey != "" {
|
||||
encoder.LevelKey = cfg.LevelKey
|
||||
}
|
||||
if cfg.TimeKey != "" {
|
||||
encoder.TimeKey = cfg.TimeKey
|
||||
}
|
||||
if cfg.CallerKey != "" {
|
||||
encoder.CallerKey = cfg.CallerKey
|
||||
}
|
||||
if cfg.UseShortFile {
|
||||
encoder.EncodeCaller = zapcore.ShortCallerEncoder
|
||||
}
|
||||
if cfg.UseJSON {
|
||||
return zapcore.NewJSONEncoder(encoder)
|
||||
}
|
||||
return zapcore.NewConsoleEncoder(encoder)
|
||||
}
|
||||
|
||||
// outputTime 保留原文件日志的时间文本格式,避免影响既有采集解析器。
|
||||
// 入参:value 为事件时间,encoder 为 Zap 的时间字段编码器。
|
||||
func outputTime(value time.Time, encoder zapcore.PrimitiveArrayEncoder) {
|
||||
var (
|
||||
second = value.UnixNano() / 1e9
|
||||
)
|
||||
var (
|
||||
milli = value.UnixNano() / 1e6 % 1e3
|
||||
)
|
||||
var (
|
||||
nano = value.UnixNano() % 1e6
|
||||
)
|
||||
encoder.AppendString(time.Unix(second, nano).Format(time.DateTime) + "." + fmt.Sprint(milli) + "+" + fmt.Sprint(nano))
|
||||
}
|
||||
|
||||
// CloseOutputs 在业务及连接全部停止后关闭所属文件,清除命名实例。
|
||||
// 返回:首个文件关闭失败的内部场景错误;所有文件均会尝试关闭。
|
||||
func CloseOutputs() error {
|
||||
var (
|
||||
first error
|
||||
)
|
||||
outputMutex.Lock()
|
||||
defer outputMutex.Unlock()
|
||||
for name, item := range outputs {
|
||||
// 文件直接写入,无缓冲;控制台 Sync 的设备错误不能覆盖文件关闭结果。
|
||||
_ = item.logger.Sync()
|
||||
if err := item.writer.Close(); err != nil {
|
||||
var (
|
||||
wrapped = outputFailure(CodeOutputClose, "close rotating log writer failed", err)
|
||||
)
|
||||
if first == nil {
|
||||
first = wrapped
|
||||
}
|
||||
}
|
||||
delete(outputs, name)
|
||||
}
|
||||
return first
|
||||
}
|
||||