Files
2024-12-21 18:19:18 +05:30

119 lines
2.5 KiB
Go

package log
import (
"context"
"go.elastic.co/ecszap"
"go.uber.org/zap"
)
const (
CORRELATION_ID_HEADER = "X-Correlation-Id"
)
type Logger struct {
log *zap.Logger
}
var Log *Logger
func initiateLogger() *zap.Logger {
config := NewCustomZapConfig()
config.EncoderConfig = ecszap.ECSCompatibleEncoderConfig(config.EncoderConfig)
log, err := config.Build(ecszap.WrapCoreOption(), zap.AddCallerSkip(1))
log = log.With(zap.String("service", "cybertron-log-enricher"))
if err != nil {
panic(err)
}
return log
}
func (l *Logger) GetLog() *zap.Logger {
return Log.log
}
func init() {
Log = &Logger{
log: initiateLogger(),
}
}
func (l *Logger) Info(msg string, fields ...zap.Field) {
l.log.Info(msg, fields...)
}
func (l *Logger) Error(msg string, fields ...zap.Field) {
l.log.Error(msg, fields...)
}
func (l *Logger) Fatal(msg string, fields ...zap.Field) {
l.log.Fatal(msg, fields...)
}
func (l *Logger) Warn(msg string, fields ...zap.Field) {
l.log.Warn(msg, fields...)
}
func (l *Logger) Panic(msg string, fields ...zap.Field) {
l.log.Panic(msg, fields...)
}
func (l *Logger) InfoWithCtx(ctx *context.Context, msg string, fields ...zap.Field) {
correlationId := getCorrelationId(ctx)
if correlationId != "" {
fields = append(fields, zap.String("correlation_id", correlationId))
}
l.log.Info(msg, fields...)
}
func (l *Logger) ErrorWithCtx(ctx *context.Context, msg string, fields ...zap.Field) {
correlationId := getCorrelationId(ctx)
if correlationId != "" {
fields = append(fields, zap.String("correlation_id", correlationId))
}
l.log.Error(msg, fields...)
}
func (l *Logger) FatalWithCtx(ctx *context.Context, msg string, fields ...zap.Field) {
correlationId := getCorrelationId(ctx)
if correlationId != "" {
fields = append(fields, zap.String("correlation_id", correlationId))
}
l.log.Fatal(msg, fields...)
}
func (l *Logger) WarnWithCtx(ctx *context.Context, msg string, fields ...zap.Field) {
correlationId := getCorrelationId(ctx)
if correlationId != "" {
fields = append(fields, zap.String("correlation_id", correlationId))
}
l.log.Warn(msg, fields...)
}
func (l *Logger) PanicWithCtx(ctx *context.Context, msg string, fields ...zap.Field) {
correlationId := getCorrelationId(ctx)
if correlationId != "" {
fields = append(fields, zap.String("correlation_id", correlationId))
}
l.log.Panic(msg, fields...)
}
func getCorrelationId(ctx *context.Context) string {
if ctx == nil {
return ""
}
correlationId, ok := (*ctx).Value(CORRELATION_ID_HEADER).(string)
if ok {
return correlationId
}
return ""
}