Refactor logging implementation by removing the custom logging utility and transitioning to direct usage of the Zap logger. Update logger configuration in the development environment and clean up related files, including the removal of unused logger configuration JSON. Ensure consistent logging practices across the application.

This commit is contained in:
windyboy
2025-11-16 13:41:51 +08:00
parent e27328378a
commit 06b2495d77
7 changed files with 13 additions and 258 deletions
-55
View File
@@ -1,55 +0,0 @@
{
"zapConfig": {
"level": "info",
"development": true,
"encoding": "json",
"encoderConfig": {
"messageKey": "msg",
"levelKey": "level",
"timeKey": "ts",
"nameKey": "logger",
"callerKey": "caller",
"stacktraceKey": "stacktrace",
"lineEnding": "",
"levelEncoder": "lowercase",
"timeEncoder": "iso8601",
"durationEncoder": "string",
"callerEncoder": "short"
},
"outputPaths": [
"stdout"
],
"errorOutputPaths": [
"stderr"
]
},
"lumberjackConfig": {
"filename": "./logs/caatsm-dev.log",
"maxSize": 50,
"maxBackups": 5,
"maxAge": 14,
"compress": false
}
}
{
"zapConfig": {
"level": "debug",
"encoding": "json",
"outputPaths": ["stdout"],
"errorOutputPaths": ["stderr"],
"encoderConfig": {
"messageKey": "message",
"levelKey": "level",
"timeKey": "time",
"nameKey": "logger",
"callerKey": "caller",
"stacktraceKey": "stacktrace",
"lineEnding": "\n",
"levelEncoder": "lowercase",
"timeEncoder": "iso8601",
"durationEncoder": "string",
"callerEncoder": "short"
}
},
"lumberjackConfig": {}
}
-1
View File
@@ -24,7 +24,6 @@ require (
go.opentelemetry.io/otel/sdk/metric v1.38.0
go.opentelemetry.io/otel/trace v1.38.0
go.uber.org/zap v1.27.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
)
require (
+3 -2
View File
@@ -1,9 +1,10 @@
package domain
import (
"caatsm/pkg/utils"
"fmt"
"time"
"go.uber.org/zap"
)
/*
@@ -95,7 +96,7 @@ type TimeReceiver struct {
}
func (h *SITAHeader) Validate() error {
log := utils.GetLogger()
log := zap.S()
// Validate SendTime format (e.g., DDHHMM)
if len(h.SendTime) != 6 {
err := "invalid send_time format"
+5 -5
View File
@@ -3,7 +3,6 @@ package parsers
import (
"caatsm/internal/domain"
"caatsm/internal/model"
"caatsm/pkg/utils"
"errors"
"fmt"
"regexp"
@@ -12,6 +11,7 @@ import (
"time"
"github.com/google/uuid"
"go.uber.org/zap"
)
const (
@@ -292,7 +292,7 @@ type Header struct {
}
func ParseHeader(fullMessage string) (Header, error) {
log := utils.GetSugaredLogger()
log := zap.S()
cleaned := cleanMessage(fullMessage)
lines := strings.Split(cleaned, "\n")
@@ -328,7 +328,7 @@ func parseStartIndicator(line string) (string, string, string, error) {
if len(parts) >= 3 && strings.HasPrefix(parts[0], StartIndicatorPrefix) {
return parts[0], parts[1], parts[2], nil
}
utils.GetSugaredLogger().Warnf("invalid start indicator line format: %s", line)
zap.S().Warnf("invalid start indicator line format: %s", line)
return "", "", "", fmt.Errorf("invalid start indicator line format: %s", line)
}
@@ -337,7 +337,7 @@ func parsePriorityAndPrimary(line string) (string, string) {
if len(parts) >= 2 {
return parts[0], parts[1]
}
utils.GetSugaredLogger().Warnf("invalid priority and primary address line format: %s", line)
zap.S().Warnf("invalid priority and primary address line format: %s", line)
return "", ""
}
@@ -389,7 +389,7 @@ func getOriginator(line string) (string, string) {
if len(match) >= 3 {
return match[1], match[2]
}
utils.GetSugaredLogger().Warnf("invalid originator line format: %s", line)
zap.S().Warnf("invalid originator line format: %s", line)
return "", ""
}
+5 -5
View File
@@ -2,10 +2,10 @@ package parsers
import (
"caatsm/internal/domain"
"caatsm/pkg/utils"
"errors"
"strings"
"go.uber.org/zap"
)
func ExtractWaypoint(message string) *domain.WayPoint {
@@ -47,7 +47,7 @@ func standardizeSpaces(s string) string {
}
func ParseWithDef(line string, parserDef *LineParser) *domain.ScheduleLine {
log := utils.GetSugaredLogger()
log := zap.S()
cleanLine := standardizeSpaces(strings.TrimSpace(line))
words := strings.Split(cleanLine, " ")
var flightSchedule = &domain.ScheduleLine{
@@ -99,7 +99,7 @@ func ParseWithDef(line string, parserDef *LineParser) *domain.ScheduleLine {
// ParseLine processes a single line of schedule data and returns a ScheduleLine object.
func ParseLine(line string) (*domain.ScheduleLine, error) {
log := utils.GetSugaredLogger()
log := zap.S()
cleanLine := strings.TrimSpace(line)
words := strings.Split(cleanLine, " ")
flightSchedule := &domain.ScheduleLine{Reference: line}
@@ -167,7 +167,7 @@ func updateFlightSchedule(flightSchedule *domain.ScheduleLine, name string, data
// parseWaypoints processes a slice of waypoint strings and returns a slice of WayPoint objects.
func parseWaypoints(target []string) ([]domain.WayPoint, error) {
log := utils.GetSugaredLogger()
log := zap.S()
points := getValidPoints(target)
if len(points) == 0 {
log.Warn("No waypoints found")
-177
View File
@@ -1,177 +0,0 @@
package utils
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
const (
TestConfigFileName = "./configs/logger.test.json"
ProdConfigFileName = "./configs/logger.json"
DevelopmentConfigFileName = "./configs/logger.dev.json"
EnvTest = "test"
EnvProd = "prod"
EnvDev = "dev"
)
type LoggerConfig struct {
ZapConfig zap.Config `json:"zapConfig"`
LumberjackConfig LumberjackConfig `json:"lumberjackConfig"`
}
type LumberjackConfig struct {
Filename string `json:"filename"`
MaxSize int `json:"maxSize"`
MaxBackups int `json:"maxBackups"`
MaxAge int `json:"maxAge"`
Compress bool `json:"compress"`
}
var (
sugar *zap.SugaredLogger
log *zap.Logger
rootDir = detectRootDir()
)
func detectRootDir() string {
_, file, _, ok := runtime.Caller(0)
if !ok {
return "."
}
// pkg/utils/log.go -> project root
return filepath.Clean(filepath.Join(filepath.Dir(file), "..", ".."))
}
func load() {
if log == nil {
env := getEnv()
// fmt.Printf("Environment: %s\n", env)
configFile := getConfigFile(env)
config, err := loadConfig(configFile)
if err != nil {
fmt.Printf("Error loading config: %v\n", err)
log, _ = zap.NewDevelopment()
sugar = log.Sugar()
return
}
var logWriter zapcore.WriteSyncer
if env == EnvProd {
logWriter = zapcore.AddSync(&lumberjack.Logger{
Filename: config.LumberjackConfig.Filename,
MaxSize: config.LumberjackConfig.MaxSize,
MaxBackups: config.LumberjackConfig.MaxBackups,
MaxAge: config.LumberjackConfig.MaxAge,
Compress: config.LumberjackConfig.Compress,
})
} else {
logWriter = zapcore.AddSync(os.Stdout)
}
encoder := zapcore.NewJSONEncoder(config.ZapConfig.EncoderConfig)
level := parseLogLevel(config.ZapConfig.Level.String())
core := zapcore.NewCore(
encoder,
logWriter,
level,
)
log = zap.New(core, zap.AddCaller(), zap.AddStacktrace(zapcore.ErrorLevel))
sugar = log.Sugar()
}
}
func GetSugaredLogger() *zap.SugaredLogger {
load()
return log.Sugar()
}
func getEnv() string {
env := os.Getenv("TELE_MODE")
if env == "" {
env = EnvDev
}
return env
}
func getConfigFile(env string) string {
switch env {
case EnvTest:
return TestConfigFileName
case EnvProd:
return ProdConfigFileName
default:
return DevelopmentConfigFileName
}
}
func loadConfig(configFile string) (LoggerConfig, error) {
file, err := openConfigFile(configFile)
if err != nil {
return LoggerConfig{}, fmt.Errorf("error opening file: %v", err)
}
defer file.Close()
var config LoggerConfig
if err := json.NewDecoder(file).Decode(&config); err != nil {
return LoggerConfig{}, fmt.Errorf("error decoding config: %v", err)
}
return config, nil
}
func GetLogger() *zap.SugaredLogger {
if sugar == nil {
load()
}
return sugar
}
func openConfigFile(configFile string) (*os.File, error) {
candidates := []string{
configFile,
filepath.Join(rootDir, strings.TrimPrefix(configFile, "./")),
}
for _, candidate := range candidates {
if candidate == "" {
continue
}
if f, err := os.Open(candidate); err == nil {
return f, nil
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
return nil, fmt.Errorf("error opening file: %v", configFile)
}
func parseLogLevel(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
case "dpanic":
return zapcore.DPanicLevel
case "panic":
return zapcore.PanicLevel
case "fatal":
return zapcore.FatalLevel
default:
return zapcore.InfoLevel
}
}
-13
View File
@@ -1,13 +0,0 @@
package utils
import "github.com/google/uuid"
func GetUuid(uuidString string) uuid.UUID {
log := GetSugaredLogger()
result, err := uuid.Parse(uuidString)
if err != nil {
log.Warnf("invalid uuid: %s", uuidString)
return uuid.New()
}
return result
}