diff --git a/cmd/api/main.go b/cmd/api/main.go index bad58f94..e7da4fbb 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -40,6 +40,10 @@ func Init() { path = flag.String("config", "./config", "config path") flag.Parse() config.Init(*path, serviceName) + + // log + utils.InitLoggerWithHook(serviceName) + // rpc rpc.Init() } diff --git a/cmd/classroom/main.go b/cmd/classroom/main.go index 59ff5b4d..3690d0e5 100644 --- a/cmd/classroom/main.go +++ b/cmd/classroom/main.go @@ -44,6 +44,9 @@ func Init() { flag.Parse() config.Init(*path, serviceName) + // log + utils.InitLoggerWithHook(serviceName) + dal.Init() InitWorkerQueue() } diff --git a/cmd/template/main.go b/cmd/template/main.go index 227ea79f..5e37dba9 100644 --- a/cmd/template/main.go +++ b/cmd/template/main.go @@ -18,25 +18,20 @@ package main import ( "flag" - "fmt" "net" "github.com/cloudwego/kitex/pkg/klog" "github.com/cloudwego/kitex/pkg/limit" "github.com/cloudwego/kitex/pkg/rpcinfo" "github.com/cloudwego/kitex/server" - "github.com/elastic/go-elasticsearch" - kitexlogrus "github.com/kitex-contrib/obs-opentelemetry/logging/logrus" etcd "github.com/kitex-contrib/registry-etcd" trace "github.com/kitex-contrib/tracer-opentracing" - "github.com/sirupsen/logrus" "github.com/west2-online/fzuhelper-server/cmd/template/dal" "github.com/west2-online/fzuhelper-server/cmd/template/rpc" "github.com/west2-online/fzuhelper-server/config" "github.com/west2-online/fzuhelper-server/kitex_gen/template/templateservice" "github.com/west2-online/fzuhelper-server/pkg/constants" - "github.com/west2-online/fzuhelper-server/pkg/eslogrus" "github.com/west2-online/fzuhelper-server/pkg/tracer" "github.com/west2-online/fzuhelper-server/pkg/utils" ) @@ -45,8 +40,6 @@ var ( serviceName = constants.TemplateServiceName path *string listenAddr string // listen port - - EsClient *elasticsearch.Client ) func Init() { @@ -55,6 +48,9 @@ func Init() { flag.Parse() config.Init(*path, serviceName) + // log + utils.InitLoggerWithHook(serviceName) + // dal dal.Init() @@ -63,11 +59,6 @@ func Init() { // rpc rpc.Init() - - // log - EsInit() - klog.SetLevel(klog.LevelDebug) - klog.SetLogger(kitexlogrus.NewLogger(kitexlogrus.WithHook(EsHookLog()))) } func main() { @@ -114,25 +105,3 @@ func main() { panic(err) } } - -func EsHookLog() *eslogrus.ElasticHook { - hook, err := eslogrus.NewElasticHook(EsClient, config.Elasticsearch.Host, logrus.DebugLevel, serviceName) - if err != nil { - panic(err) - } - - return hook -} - -// InitEs 初始化es -func EsInit() { - esConn := fmt.Sprintf("http://%s", config.Elasticsearch.Addr) - cfg := elasticsearch.Config{ - Addresses: []string{esConn}, - } - client, err := elasticsearch.NewClient(cfg) - if err != nil { - panic(err) - } - EsClient = client -} diff --git a/cmd/user/main.go b/cmd/user/main.go index 4efcc502..ac508a41 100644 --- a/cmd/user/main.go +++ b/cmd/user/main.go @@ -42,6 +42,9 @@ func Init() { path = flag.String("config", "./config", "config path") flag.Parse() config.Init(*path, serviceName) + + // log + utils.InitLoggerWithHook(serviceName) } func main() { diff --git a/go.mod b/go.mod index 423068ba..d9fcb581 100644 --- a/go.mod +++ b/go.mod @@ -10,13 +10,12 @@ require ( github.com/cloudwego/kitex v0.11.3 github.com/elastic/go-elasticsearch v0.0.0 github.com/fsnotify/fsnotify v1.7.0 - github.com/kitex-contrib/obs-opentelemetry/logging/logrus v0.0.0-20240515092919-1f776656cb66 + github.com/kitex-contrib/obs-opentelemetry/logging/zap v0.0.0-20241010093641-c58c6426d043 github.com/kitex-contrib/registry-etcd v0.2.5 github.com/kitex-contrib/tracer-opentracing v0.0.3 github.com/opentracing/opentracing-go v1.2.0 github.com/rabbitmq/amqp091-go v1.10.0 github.com/redis/go-redis/v9 v9.6.1 - github.com/sirupsen/logrus v1.9.3 github.com/spf13/viper v1.19.0 github.com/uber/jaeger-client-go v2.30.0+incompatible github.com/west2-online/jwch v0.1.4 @@ -57,6 +56,7 @@ require ( github.com/pkg/errors v0.9.1 // indirect github.com/sagikazarmark/locafero v0.6.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/sirupsen/logrus v1.9.3 // indirect github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d // indirect github.com/smartystreets/goconvey v1.6.4 // indirect github.com/sourcegraph/conc v0.3.0 // indirect diff --git a/go.sum b/go.sum index 52d25ee7..759ee9c9 100644 --- a/go.sum +++ b/go.sum @@ -302,8 +302,8 @@ github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7V github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/kitex-contrib/obs-opentelemetry/logging/logrus v0.0.0-20240515092919-1f776656cb66 h1:KHEWSTCleXom38JQodofbpY7HNR2KQ4+ypIurCPFy/A= -github.com/kitex-contrib/obs-opentelemetry/logging/logrus v0.0.0-20240515092919-1f776656cb66/go.mod h1:naiLX9zwKBzVA41wtvvmtSZdbCihqIT9RnOb8GZv8A4= +github.com/kitex-contrib/obs-opentelemetry/logging/zap v0.0.0-20241010093641-c58c6426d043 h1:JlH4bwMt51FxWgMAmoCYmorPvYsaDVGSiyA5JPwusoc= +github.com/kitex-contrib/obs-opentelemetry/logging/zap v0.0.0-20241010093641-c58c6426d043/go.mod h1:iedxajZANlvR0u8ODF8TJ7ZAcx6Fg+CMgJT+WsGH5eg= github.com/kitex-contrib/registry-etcd v0.2.5 h1:16On5GQAmN9tdbFy95QtwGH3aTWnW/BfdvdDmzLIytE= github.com/kitex-contrib/registry-etcd v0.2.5/go.mod h1:Imgvy+EkqExHuJs4+VFK0g1bFWHaCJ0KuK1sofWYZf4= github.com/kitex-contrib/tracer-opentracing v0.0.3 h1:8SI0OrHTQ8u6eWpemnuaecMBSEVEvWKCWxg2HnnONQU= @@ -367,7 +367,6 @@ github.com/nats-io/nkeys v0.4.7 h1:RwNJbbIdYCoClSDNY7QVKZlyb/wfT6ugvFCiKy6vDvI= github.com/nats-io/nkeys v0.4.7/go.mod h1:kqXRgRDPlGy7nGaEDMuYzmiJCIAAWDK0IMBtDmGD0nc= github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nyaruka/phonenumbers v1.0.55/go.mod h1:sDaTZ/KPX5f8qyV9qN+hIm+4ZBARJrupC6LuhshJq1U= github.com/nyaruka/phonenumbers v1.4.0 h1:ddhWiHnHCIX3n6ETDA58Zq5dkxkjlvgrDWM2OHHPCzU= @@ -716,8 +715,9 @@ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLks gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8= diff --git a/pkg/client/es.go b/pkg/client/es.go new file mode 100644 index 00000000..20d28b23 --- /dev/null +++ b/pkg/client/es.go @@ -0,0 +1,41 @@ +/* +Copyright 2024 The west2-online Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package client + +import ( + "errors" + "fmt" + + "github.com/elastic/go-elasticsearch" + + "github.com/west2-online/fzuhelper-server/config" +) + +func NewEsClient() (*elasticsearch.Client, error) { + if config.Elasticsearch == nil { + return nil, errors.New("elasticsearch config is nil") + } + esConn := fmt.Sprintf("http://%s", config.Elasticsearch.Addr) + cfg := elasticsearch.Config{ + Addresses: []string{esConn}, + } + client, err := elasticsearch.NewClient(cfg) + if err != nil { + return nil, fmt.Errorf("Get es clint failed,error: %v", err) + } + return client, nil +} diff --git a/pkg/eslogrus/eslogrus.go b/pkg/eslogrus/eslogrus.go deleted file mode 100644 index 6574ebaf..00000000 --- a/pkg/eslogrus/eslogrus.go +++ /dev/null @@ -1,151 +0,0 @@ -/* -Copyright 2024 The west2-online Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package eslogrus - -import ( - "bytes" - "context" - "encoding/json" - "log" - "strings" - "time" - - elastic "github.com/elastic/go-elasticsearch" - "github.com/elastic/go-elasticsearch/esapi" - "github.com/sirupsen/logrus" -) - -// ElasticHook is a logrus -// hook for ElasticSearch -type ElasticHook struct { - client *elastic.Client // es的客户端 - host string // es 的 host - index IndexNameFunc // 获取索引的名字 - levels []logrus.Level // 日志的级别 info,error - ctx context.Context // 上下文 - ctxCancel context.CancelFunc // 上下文cancel的函数, - fireFunc fireFunc // 需要实现这个 -} - -// 发送到es的信息结构 -type message struct { - Host string - Timestamp string `json:"@timestamp"` - Message string - Data logrus.Fields - Level string -} - -// IndexNameFunc get index name -type IndexNameFunc func() string - -type fireFunc func(entry *logrus.Entry, hook *ElasticHook) error - -// NewElasticHook 新建一个es hook对象 -func NewElasticHook(client *elastic.Client, host string, level logrus.Level, index string) (*ElasticHook, error) { - return NewElasticHookWithFunc(client, host, level, func() string { return index }) -} - -func NewElasticHookWithFunc(client *elastic.Client, host string, level logrus.Level, indexFunc IndexNameFunc) (*ElasticHook, error) { - return newHookFuncAndFireFunc(client, host, level, indexFunc, syncFireFunc) -} - -// 新建一个hook -func newHookFuncAndFireFunc(client *elastic.Client, host string, level logrus.Level, indexFunc IndexNameFunc, fireFunc fireFunc) (*ElasticHook, error) { - var levels []logrus.Level - for _, l := range []logrus.Level{ - logrus.PanicLevel, - logrus.FatalLevel, - logrus.ErrorLevel, - logrus.WarnLevel, - logrus.InfoLevel, - logrus.DebugLevel, - } { - if l <= level { - levels = append(levels, l) - } - } - - ctx, cancel := context.WithCancel(context.TODO()) - - return &ElasticHook{ - client: client, - host: host, - index: indexFunc, - levels: levels, - ctx: ctx, - ctxCancel: cancel, - fireFunc: fireFunc, - }, nil -} - -// createMessage 创建信息 -func createMessage(entry *logrus.Entry, hook *ElasticHook) *message { - level := entry.Level.String() - - if e, ok := entry.Data[logrus.ErrorKey]; ok && e != nil { - if err, ok := e.(error); ok { - entry.Data[logrus.ErrorKey] = err.Error() - } - } - - return &message{ - hook.host, - entry.Time.UTC().Format(time.RFC3339Nano), - entry.Message, - entry.Data, - strings.ToUpper(level), - } -} - -// syncFireFunc 异步发送 -func syncFireFunc(entry *logrus.Entry, hook *ElasticHook) error { - data, err := json.Marshal(createMessage(entry, hook)) - if err != nil { - return err - } - - req := esapi.IndexRequest{ - Index: hook.index(), - Body: bytes.NewReader(data), - Refresh: "true", - } - - res, err := req.Do(hook.ctx, hook.client) - if err != nil { - log.Fatalf("Error getting response: %s", err) - } - - var r map[string]interface{} - if err = json.NewDecoder(res.Body).Decode(&r); err != nil { - log.Printf("Error parsing the response body: %s", err) - } else { - // Print the response status and indexed document version. - log.Printf("[%s] %s; version=%d", res.Status(), r["result"], int(r["_version"].(float64))) - } - return err -} - -// Fire 实现 logrus hook 必须要的接口函数 -func (hook *ElasticHook) Fire(entry *logrus.Entry) error { - return hook.fireFunc(entry, hook) -} - -// Levels 实现 logrus hook 必须要的接口函数 -func (hook *ElasticHook) Levels() []logrus.Level { - return hook.levels -} diff --git a/pkg/logger/eshook.go b/pkg/logger/eshook.go new file mode 100644 index 00000000..edae3d06 --- /dev/null +++ b/pkg/logger/eshook.go @@ -0,0 +1,101 @@ +/* +Copyright 2024 The west2-online Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package logger + +import ( + "bytes" + "context" + "encoding/json" + "log" + "strings" + "time" + + elastic "github.com/elastic/go-elasticsearch" + "github.com/elastic/go-elasticsearch/esapi" + "go.uber.org/zap/zapcore" +) + +// ElasticHook is a zap hook for ElasticSearch +type ElasticHook struct { + client *elastic.Client // es 的客户端 + host string // es 的 host + index string // 获取索引的名字 + ctx context.Context + cancel func() +} + +func NewElasticHook(client *elastic.Client, host string, index string) *ElasticHook { + hook := defaultHookConfig() + + hook.client = client + hook.host = host + hook.index = index + + return hook +} + +func defaultHookConfig() *ElasticHook { + ctx, cancel := context.WithCancel(context.Background()) + return &ElasticHook{ + ctx: ctx, + cancel: cancel, + } +} + +// 发送到 es 的信息结构 +type message struct { + Host string + Timestamp string `json:"@timestamp"` + Message string + Level string +} + +func createMessage(entry *zapcore.Entry, hook *ElasticHook) *message { + return &message{ + Host: hook.host, + Timestamp: entry.Time.UTC().Format(time.RFC3339), + Message: entry.Message, + Level: strings.ToUpper(entry.Level.String()), + } +} + +func (hook *ElasticHook) Fire(entry zapcore.Entry) error { + data, err := json.Marshal(createMessage(&entry, hook)) + if err != nil { + return err + } + + req := esapi.IndexRequest{ + Index: hook.index, + Body: bytes.NewReader(data), + Refresh: "true", + } + + res, err := req.Do(hook.ctx, hook.client) + if err != nil { + log.Fatalf("Error getting response: %s", err) + } + + var r map[string]interface{} + if err = json.NewDecoder(res.Body).Decode(&r); err != nil { + log.Printf("Error parsing the response body: %s", err) + } else { + // Print the response status and indexed document version. + log.Printf("[%s] %s; version=%d", res.Status(), r["result"], int(r["_version"].(float64))) + } + return err +} diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go index ab9f5dc8..8eedca44 100644 --- a/pkg/logger/logger.go +++ b/pkg/logger/logger.go @@ -17,94 +17,67 @@ limitations under the License. package logger import ( - "sync" + "os" + kitexzap "github.com/kitex-contrib/obs-opentelemetry/logging/zap" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) -var ( - LoggerObj *zap.SugaredLogger - once sync.Once -) +type Config struct { + Enc zapcore.Encoder + Ws zapcore.WriteSyncer + lvl zapcore.Level +} -// 初始化 Logger 的函数 -func initLogger() { - // 配置 zap 的日志等级和输出格式 - config := zap.Config{ - Level: zap.NewAtomicLevelAt(zap.DebugLevel), // 设置日志等级 - Development: false, // 非开发模式 - Encoding: "console", // 输出格式(json 或 console) - OutputPaths: []string{"stdout"}, // 输出目标 - ErrorOutputPaths: []string{"stderr"}, // 错误输出目标 - EncoderConfig: zapcore.EncoderConfig{ - TimeKey: "time", - LevelKey: "level", - NameKey: "logger", - CallerKey: "caller", - MessageKey: "msg", - StacktraceKey: "stacktrace", - LineEnding: zapcore.DefaultLineEnding, - EncodeLevel: zapcore.CapitalLevelEncoder, // 日志等级大写 - EncodeTime: zapcore.ISO8601TimeEncoder, // 时间格式 - EncodeDuration: zapcore.StringDurationEncoder, - EncodeCaller: zapcore.ShortCallerEncoder, - }, +func NewLogger(lvl zapcore.Level, cfg Config, options ...zap.Option) *kitexzap.Logger { + if cfg.Enc == nil { + cfg.Enc = defaultEnc() } - logger, err := config.Build(zap.AddCallerSkip(1)) // 创建基础 Logger - if err != nil { - panic(err) + if cfg.Ws == nil { + cfg.Ws = defaultWs() } - - // 创建 SugaredLogger - LoggerObj = logger.Sugar() -} - -// 确保 LoggerObj 只初始化一次 -// 使用 init() 函数来替代 syncOnce 是个方法,而且不需要额外的代码来进行 check -// 但是这样损失了更多的 DIY 特性,比如可以在初始化的时候传入参数 -func ensureLoggerInit() { - once.Do(func() { - initLogger() - }) -} - -func Fatalf(template string, args ...interface{}) { - ensureLoggerInit() - LoggerObj.Fatalf(template, args...) + cfg.lvl = lvl + + var ops []kitexzap.Option + ops = append(ops, kitexzap.WithCoreEnc(cfg.Enc)) + ops = append(ops, kitexzap.WithCoreWs(cfg.Ws)) + ops = append(ops, kitexzap.WithCoreLevel(zap.NewAtomicLevelAt(cfg.lvl))) + ops = append(ops, kitexzap.WithZapOptions(options...)) + return kitexzap.NewLogger(ops...) } -func Errorf(template string, args ...interface{}) { - ensureLoggerInit() - LoggerObj.Errorf(template, args...) +func DefaultLogger(options ...zap.Option) *kitexzap.Logger { + var ops []kitexzap.Option + ops = append(ops, kitexzap.WithCoreEnc(defaultEnc())) + ops = append(ops, kitexzap.WithCoreWs(defaultWs())) + ops = append(ops, kitexzap.WithCoreLevel(zap.NewAtomicLevelAt(defaultLvl()))) + ops = append(ops, kitexzap.WithZapOptions(options...)) + return kitexzap.NewLogger(ops...) } -func Infof(template string, args ...interface{}) { - ensureLoggerInit() - LoggerObj.Infof(template, args...) -} - -func Debugf(template string, args ...interface{}) { - ensureLoggerInit() - LoggerObj.Debugf(template, args...) -} - -func Fatal(args ...interface{}) { - ensureLoggerInit() - LoggerObj.Fatal(args) -} +func defaultEnc() zapcore.Encoder { + cfg := zapcore.EncoderConfig{ + TimeKey: "time", + LevelKey: "level", + NameKey: "logger", + CallerKey: "caller", + MessageKey: "msg", + StacktraceKey: "stacktrace", + LineEnding: zapcore.DefaultLineEnding, + EncodeLevel: zapcore.CapitalLevelEncoder, // 日志等级大写 + EncodeTime: zapcore.ISO8601TimeEncoder, // 时间格式 + EncodeDuration: zapcore.StringDurationEncoder, + EncodeCaller: zapcore.ShortCallerEncoder, + } -func Info(args ...interface{}) { - ensureLoggerInit() - LoggerObj.Info(args) + return zapcore.NewConsoleEncoder(cfg) } -func Error(args ...interface{}) { - ensureLoggerInit() - LoggerObj.Error(args) +func defaultWs() zapcore.WriteSyncer { + return os.Stdout } -func Debug(args ...interface{}) { - ensureLoggerInit() - LoggerObj.Debug(args) +func defaultLvl() zapcore.Level { + return zapcore.DebugLevel } diff --git a/pkg/logger/output.go b/pkg/logger/output.go new file mode 100644 index 00000000..fd55023d --- /dev/null +++ b/pkg/logger/output.go @@ -0,0 +1,55 @@ +/* +Copyright 2024 The west2-online Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package logger + +import "github.com/cloudwego/kitex/pkg/klog" + +func init() { + klog.SetLogger(DefaultLogger()) +} + +func Fatalf(template string, args ...interface{}) { + klog.Fatalf(template, args...) +} + +func Errorf(template string, args ...interface{}) { + klog.Errorf(template, args...) +} + +func Infof(template string, args ...interface{}) { + klog.Infof(template, args...) +} + +func Debugf(template string, args ...interface{}) { + klog.Debugf(template, args...) +} + +func Fatal(args ...interface{}) { + klog.Fatal(args) +} + +func Info(args ...interface{}) { + klog.Info(args) +} + +func Error(args ...interface{}) { + klog.Error(args) +} + +func Debug(args ...interface{}) { + klog.Debug(args) +} diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index b8067644..cf9ce4a3 100644 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -25,6 +25,12 @@ import ( "strings" "time" + "github.com/cloudwego/kitex/pkg/klog" + "go.uber.org/zap" + + "github.com/west2-online/fzuhelper-server/pkg/client" + "github.com/west2-online/fzuhelper-server/pkg/logger" + "github.com/west2-online/fzuhelper-server/pkg/constants" "github.com/west2-online/jwch" @@ -55,6 +61,27 @@ func GetMQUrl() (string, error) { return url, nil } +func GetEsHost() (string, error) { + if config.Elasticsearch == nil { + return "", errors.New("elasticsearch not found") + } + + return config.Elasticsearch.Host, nil +} + +// InitLoggerWithHook 初始化带有EsHook的logger +// index: 索引的名字 +func InitLoggerWithHook(index string) { + c, err := client.NewEsClient() + if err != nil { + panic(err) + } + + hook := logger.NewElasticHook(c, config.Elasticsearch.Host, index) + v := logger.DefaultLogger(zap.Hooks(hook.Fire)) + klog.SetLogger(v) +} + func AddrCheck(addr string) bool { l, err := net.Listen("tcp", addr) if err != nil {