| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- // Package log provides the colored console logger setup and the business
- // Record* helpers, ported from sdf-serve pkg/common/log.
- package log
- import (
- "context"
- stdErrors "errors"
- "fmt"
- "udeServer/internal/apierr"
- "udeServer/internal/response"
- "github.com/zeromicro/go-zero/core/logx"
- "go.uber.org/zap"
- "go.uber.org/zap/zapcore"
- )
- // SetupLoggerWithColor replaces the global zap logger with a colored
- // development configuration. It only takes effect when Log.Mode is "console";
- // otherwise go-zero keeps its default logging behaviour.
- func SetupLoggerWithColor(conf logx.LogConf) {
- if conf.Mode != "console" {
- return
- }
- cfg := zap.NewDevelopmentConfig()
- cfg.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
- cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
- cfg.Level = zap.NewAtomicLevelAt(getZapLevel(conf.Level))
- logger, err := cfg.Build()
- if err != nil {
- panic(err)
- }
- zap.ReplaceGlobals(logger)
- }
- func getZapLevel(level string) zapcore.Level {
- switch level {
- case "debug":
- return zapcore.DebugLevel
- case "info":
- return zapcore.InfoLevel
- case "warn":
- return zapcore.WarnLevel
- case "error":
- return zapcore.ErrorLevel
- default:
- return zapcore.InfoLevel
- }
- }
- // RecordError logs an error. For HTTP-aware errors (apierr.Error) the mapped
- // business code is reported as well; anything else is logged as a system
- // error with its full cause.
- func RecordError(ctx context.Context, err error) {
- var apiErr *apierr.Error
- if stdErrors.As(err, &apiErr) {
- logx.WithContext(ctx).Errorf("【BUSINESS_ERROR】Status:%d, Code:%d, Msg:%s",
- apiErr.Status, response.Code(err), apiErr.Msg)
- } else {
- logx.WithContext(ctx).Errorf("【SYSTEM_ERROR】Cause: %+v", err)
- }
- }
- // RecordInfo logs ordinary business information.
- func RecordInfo(ctx context.Context, format string, args ...interface{}) {
- logx.WithContext(ctx).Infof("【BUSINESS_INFO】"+format, args...)
- }
- // RecordWarn logs issues worth attention that do not necessarily alert.
- // go-zero logx has no Warn level, so warnings go through the global zap
- // logger (same as sdf-serve); the ctx parameter stays for call-site
- // compatibility.
- func RecordWarn(ctx context.Context, format string, args ...interface{}) {
- zap.L().Warn(fmt.Sprintf("【BUSINESS_WARN】"+format, args...))
- }
- // RecordDebug logs development-time debug information.
- func RecordDebug(ctx context.Context, format string, args ...interface{}) {
- logx.WithContext(ctx).Debugf("【BUSINESS_DEBUG】"+format, args...)
- }
|