接入腾讯云日志服务

This commit is contained in:
2025-02-28 12:34:13 +08:00
parent f251df5ce3
commit 4973b8471e
6 changed files with 123 additions and 4 deletions

49
logger/cls.go Normal file
View File

@@ -0,0 +1,49 @@
package logger
import (
"encoding/json"
"game-driver/config"
tencentcloud_cls_sdk_go "github.com/tencentcloud/tencentcloud-cls-sdk-go"
"time"
)
type TenCls struct {
p *tencentcloud_cls_sdk_go.AsyncProducerClient
key string
}
func (t *TenCls) Write(p []byte) (n int, err error) {
s := make(map[string]string)
_ = json.Unmarshal(p, &s)
s["key"] = t.key
delete(s, "ts")
clsLog := tencentcloud_cls_sdk_go.NewCLSLog(time.Now().Unix(), s)
err = t.p.SendLog(config.C.Log.TencentCLS.TopicID, clsLog, nil)
return len(p), err
}
func (t *TenCls) Start() {
t.p.Start()
}
func (t *TenCls) Close() error {
return t.p.Close(60_000)
}
func NewTenCls(code string) (*TenCls, error) {
producerConfig := tencentcloud_cls_sdk_go.GetDefaultAsyncProducerClientConfig()
producerConfig.Endpoint = config.C.Log.TencentCLS.Endpoint
producerConfig.AccessKeyID = config.C.Log.TencentCLS.SecretID
producerConfig.AccessKeySecret = config.C.Log.TencentCLS.SecretKey
producerInstance, err := tencentcloud_cls_sdk_go.NewAsyncProducerClient(producerConfig)
if err != nil {
return nil, err
}
t := &TenCls{
p: producerInstance,
key: code,
}
return t, nil
}

View File

@@ -13,7 +13,7 @@ func DefaultLogger() {
zap.ReplaceGlobals(logger)
}
func InitLogger() {
func InitDevLogger() {
// 解析日志级别
level, err := zapcore.ParseLevel(config.C.Log.Level)
if err != nil {
@@ -38,6 +38,31 @@ func InitLogger() {
zap.ReplaceGlobals(logger)
}
func InitProLogger(cls *TenCls) {
// 解析日志级别
level, err := zapcore.ParseLevel(config.C.Log.Level)
if err != nil {
log.Panicln("日志级别配置错误: ", err)
}
// 默认开发模式
nc := zap.NewProductionEncoderConfig()
// json 格式输出
cn := zapcore.NewJSONEncoder(nc)
// 多个输出
mws := zapcore.NewMultiWriteSyncer(zapcore.AddSync(cls), zapcore.AddSync(os.Stdout))
// 核心配置
core := zapcore.NewCore(cn, mws, level)
// 构建 logger
logger := zap.New(core, zap.AddCaller())
// 替换全局 logger
zap.ReplaceGlobals(logger)
}
func Sync() {
zap.L().Sync()
}