logger

package
v0.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 18, 2026 License: Apache-2.0 Imports: 15 Imported by: 8

README

Logger

Logging system built on logrus.

Features

  • JSON logging
  • Context tracing
  • Data desensitization
  • Multiple outputs: console, file, Elasticsearch, OpenSearch, Meilisearch
  • Fixed-length masking

Quick Start

import (
    "context"
    "github.com/ncobase/ncore/logging/logger"
    "github.com/ncobase/ncore/logging/logger/config"
)

// Basic setup
cleanup, err := logger.New(&config.Config{
    Level:  4, // Info level
    Format: "json",
    Output: "stdout",
})
if err != nil {
    panic(err)
}
defer cleanup()

// Logging
ctx := context.Background()
logger.Info(ctx, "Application started")
logger.WithFields(ctx, logrus.Fields{
    "user_id": "123",
    "action":  "login",
}).Info("User login")

Data Desensitization

Automatically protects sensitive data in logs with fixed-length masking:

// Configuration
&config.Config{
    Level:  4,
    Format: "json",
    Output: "file",
    OutputFile: "./logs/app.log",
    Desensitization: &config.Desensitization{
        Enabled:         true,
        UseFixedLength:  true,  // All sensitive data → "********"
        FixedMaskLength: 8,
        MaskChar:        "*",
    },
}

// Usage - sensitive fields automatically masked
logger.WithFields(ctx, logrus.Fields{
    "username": "john",
    "password": "secret123",     // → "********"
    "email":    "john@test.com", // → "********"
    "token":    "eyJhbGci...",   // → "********"
}).Info("User authenticated")
Deep Structure Support

Automatically processes nested objects, arrays, and maps:

type User struct {
    Username string            `json:"username"`
    Password string            `json:"password"`
    Profile  map[string]string `json:"profile"`
    APIKeys  []string          `json:"api_keys"`
}

user := User{
    Username: "john",
    Password: "secret",
    Profile:  map[string]string{"email": "john@test.com"},
    APIKeys:  []string{"sk_test_123", "pk_live_456"},
}

// All nested sensitive data automatically masked
logger.WithFields(ctx, logrus.Fields{
    "user": user, // Deep structure processed
}).Info("User created")

Configuration

File Output
&config.Config{
    Output:     "file",
    OutputFile: "./logs/app.log", // Daily rotation
}
Search Engines
// Elasticsearch
Elasticsearch: &config.Elasticsearch{
    Addresses: []string{"http://localhost:9200"},
    Username:  "elastic",
    Password:  "password",
}

// OpenSearch  
OpenSearch: &config.OpenSearch{
    Addresses: []string{"https://localhost:9200"},
    Username:  "admin",
    Password:  "admin",
}

// Meilisearch
Meilisearch: &config.Meilisearch{
    Host:   "http://localhost:7700",
    APIKey: "masterKey",
}
Custom Desensitization
Desensitization: &config.Desensitization{
    Enabled:               true,
    UseFixedLength:        true,
    FixedMaskLength:       8,
    SensitiveFields:       []string{"password", "token", "secret", "api_key"},
    CustomPatterns:        []string{`\b\d{4}-\d{4}-\d{4}-\d{4}\b`}, // Credit cards
    EnableDefaultPatterns: true,  // Enable built-in patterns (credit cards, emails, etc.)
    ExactFieldMatch:       false, // false: fuzzy match, true: exact match
}

Field Matching Modes:

  • ExactFieldMatch: false (default): Fuzzy match - "password" matches "user_password", "password_hash"
  • ExactFieldMatch: true: Exact match - "password" only matches "password"

Request Tracing

func HandleRequest(w http.ResponseWriter, r *http.Request) {
    ctx, traceID := logger.EnsureTraceID(r.Context())
    w.Header().Set("X-Trace-ID", traceID)
    
    logger.Info(ctx, "Request started")
    // All logs in this context include the same trace ID
    processRequest(ctx)
    logger.Info(ctx, "Request completed")
}

Production Configuration

logger:
  level: 4
  format: json
  output: file
  output_file: /var/log/app.log
  
  desensitization:
    enabled: true
    use_fixed_length: true
    fixed_mask_length: 8
    enable_default_patterns: true # Built-in patterns for credit cards, emails, etc.
    
  elasticsearch:
    addresses: ["http://es:9200"]
    username: elastic
    password: ${ES_PASSWORD}

API Reference

// Initialization
func New(c *config.Config) (func(), error)

// Logging
func Debug/Info/Warn/Error/Fatal/Panic(ctx context.Context, args ...any)
func Debugf/Infof/Warnf/Errorf/Fatalf/Panicf(ctx context.Context, format string, args ...any)
func WithFields(ctx context.Context, fields logrus.Fields) *logrus.Entry

// Tracing
func EnsureTraceID(ctx context.Context) (context.Context, string)

Log Levels

Level Value Usage
Trace 6 Detailed debugging
Debug 5 Debug information
Info 4 General information
Warn 3 Warnings
Error 2 Errors
Fatal 1 Critical errors
Panic 0 System panic

Documentation

Index

Constants

View Source
const (
	VersionKey      = "version"
	SpanTitleKey    = "title"
	SpanFunctionKey = "function"
)

Key constants

Variables

View Source
var ProviderSet = wire.NewSet(ProvideLogger)

ProviderSet is the wire provider set for the logger package

Functions

func AddHook

func AddHook(hook logrus.Hook)

AddHook adds a hook to the logger

func Debug

func Debug(ctx context.Context, args ...any)

Debug logs debug message

func Debugf

func Debugf(ctx context.Context, format string, args ...any)

Debugf logs debug message with format

func EnsureTraceID

func EnsureTraceID(ctx context.Context) (context.Context, string)

EnsureTraceID ensures that a trace ID exists in the context.

func Error

func Error(ctx context.Context, args ...any)

Error logs error message

func Errorf

func Errorf(ctx context.Context, format string, args ...any)

Errorf logs error message with format

func Fatal

func Fatal(ctx context.Context, args ...any)

Fatal logs fatal message

func Fatalf

func Fatalf(ctx context.Context, format string, args ...any)

Fatalf logs fatal message with format

func Info

func Info(ctx context.Context, args ...any)

Info logs info message

func Infof

func Infof(ctx context.Context, format string, args ...any)

Infof logs info message with format

func New

func New(c *config.Config) (func(), error)

New creates new logger

func Panic

func Panic(ctx context.Context, args ...any)

Panic logs panic message

func Panicf

func Panicf(ctx context.Context, format string, args ...any)

Panicf logs panic message with format

func RegisterHookFactory added in v0.2.1

func RegisterHookFactory(hookType HookType, factory HookFactory)

RegisterHookFactory registers a hook factory for a given type. This is called by hook packages in their init() functions.

func SetOutput

func SetOutput(out io.Writer)

SetOutput sets the output destination for the logger

func SetVersion

func SetVersion(v string)

SetVersion sets the version for logging

func Trace

func Trace(ctx context.Context, args ...any)

Trace logs trace message

func Tracef

func Tracef(ctx context.Context, format string, args ...any)

Tracef logs trace message with format

func Warn

func Warn(ctx context.Context, args ...any)

Warn logs warn message

func Warnf

func Warnf(ctx context.Context, format string, args ...any)

Warnf logs warn message with format

func WithFields

func WithFields(ctx context.Context, fields logrus.Fields) *logrus.Entry

WithFields returns an entry with the given fields

Types

type Desensitizer

type Desensitizer struct {
	// contains filtered or unexported fields
}

Desensitizer handles sensitive data masking in log fields

func NewDesensitizer

func NewDesensitizer(cfg *config.Desensitization) *Desensitizer

NewDesensitizer creates a new desensitizer instance

func (*Desensitizer) DeepDesensitize

func (d *Desensitizer) DeepDesensitize(data any) any

DeepDesensitize provides standalone deep desensitization

func (*Desensitizer) DesensitizeFields

func (d *Desensitizer) DesensitizeFields(fields logrus.Fields) logrus.Fields

DesensitizeFields processes log fields and masks sensitive data

type HookFactory added in v0.2.1

type HookFactory func(cfg *config.Config) (logrus.Hook, error)

HookFactory creates a logrus hook from configuration

func GetHookFactory added in v0.2.1

func GetHookFactory(hookType HookType) (HookFactory, bool)

GetHookFactory returns the factory for a given hook type

type HookType added in v0.2.1

type HookType string

HookType represents the type of logging hook

const (
	HookElasticsearch HookType = "elasticsearch"
	HookOpenSearch    HookType = "opensearch"
	HookMeilisearch   HookType = "meilisearch"
)

func GetRegisteredHooks added in v0.2.1

func GetRegisteredHooks() []HookType

GetRegisteredHooks returns list of registered hook types

type Logger

type Logger struct {
	*logrus.Logger
	// contains filtered or unexported fields
}

Logger represents logger instance

func ProvideLogger added in v0.2.0

func ProvideLogger(cfg *config.Config) (*Logger, func(), error)

ProvideLogger initializes and returns the standard logger

func StdLogger

func StdLogger() *Logger

StdLogger returns the single logger instance

func (*Logger) AddHook

func (l *Logger) AddHook(hook logrus.Hook)

AddHook adds a hook to the logger

func (*Logger) Debug

func (l *Logger) Debug(ctx context.Context, args ...any)

Debug logs a debug message

func (*Logger) Debugf

func (l *Logger) Debugf(ctx context.Context, format string, args ...any)

Debugf logs a debug message with format

func (*Logger) Error

func (l *Logger) Error(ctx context.Context, args ...any)

Error logs an error message

func (*Logger) Errorf

func (l *Logger) Errorf(ctx context.Context, format string, args ...any)

Errorf logs an error message with format

func (*Logger) Fatal

func (l *Logger) Fatal(ctx context.Context, args ...any)

Fatal logs a fatal message

func (*Logger) Fatalf

func (l *Logger) Fatalf(ctx context.Context, format string, args ...any)

Fatalf logs a fatal message with format

func (*Logger) Info

func (l *Logger) Info(ctx context.Context, args ...any)

Info logs an info message

func (*Logger) Infof

func (l *Logger) Infof(ctx context.Context, format string, args ...any)

Infof logs an info message with format

func (*Logger) Init

func (l *Logger) Init(c *config.Config) (func(), error)

Init initializes the logger with the given configuration

func (*Logger) Panic

func (l *Logger) Panic(ctx context.Context, args ...any)

Panic logs a panic message

func (*Logger) Panicf

func (l *Logger) Panicf(ctx context.Context, format string, args ...any)

Panicf logs a panic message with format

func (*Logger) SetOutput

func (l *Logger) SetOutput(out io.Writer)

SetOutput sets the output destination for the logger

func (*Logger) SetVersion

func (l *Logger) SetVersion(v string)

SetVersion sets the version for logging

func (*Logger) Trace

func (l *Logger) Trace(ctx context.Context, args ...any)

Trace logs a trace message

func (*Logger) Tracef

func (l *Logger) Tracef(ctx context.Context, format string, args ...any)

Tracef logs a trace message with format

func (*Logger) Warn

func (l *Logger) Warn(ctx context.Context, args ...any)

Warn logs a warn message

func (*Logger) Warnf

func (l *Logger) Warnf(ctx context.Context, format string, args ...any)

Warnf logs a warn message with format

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL