logger

package
v0.1.18 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2025 License: Apache-2.0 Imports: 17 Imported by: 8

README

ncore/logger

A powerful logging system built on logrus with multi-output support, search engine integrations, and data desensitization.

Features

  • Multiple log levels with structured JSON logging
  • Context-aware tracing with automatic trace ID propagation
  • Data desensitization with deep structure support
  • Multiple outputs: console, file (auto-rotation), Elasticsearch, OpenSearch, Meilisearch
  • Fixed-length masking to prevent sensitive data length disclosure

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:

// Secure configuration (recommended)
&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

This section is empty.

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 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 added in v0.1.4

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

Desensitizer handles sensitive data masking in log fields

func NewDesensitizer added in v0.1.4

func NewDesensitizer(cfg *config.Desensitization) *Desensitizer

NewDesensitizer creates a new desensitizer instance

func (*Desensitizer) DeepDesensitize added in v0.1.4

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

DeepDesensitize provides standalone deep desensitization

func (*Desensitizer) DesensitizeFields added in v0.1.4

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

DesensitizeFields processes log fields and masks sensitive data

type ElasticSearchHook

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

ElasticSearchHook represents an Elasticsearch log hook

func NewElasticSearchHook added in v0.1.17

func NewElasticSearchHook(client *elastic.Client, cfg *config.Config) *ElasticSearchHook

NewElasticSearchHook creates new Elasticsearch hook

func (*ElasticSearchHook) Fire

func (h *ElasticSearchHook) Fire(entry *logrus.Entry) error

Fire sends log entry to Elasticsearch

func (*ElasticSearchHook) Levels

func (h *ElasticSearchHook) Levels() []logrus.Level

Levels returns all log levels

type Logger

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

Logger represents logger instance

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

type MeiliSearchHook

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

MeiliSearchHook represents a MeiliSearch log hook

func NewMeiliSearchHook added in v0.1.17

func NewMeiliSearchHook(client *meili.Client, cfg *config.Config) *MeiliSearchHook

NewMeiliSearchHook creates new MeiliSearch hook

func (*MeiliSearchHook) Fire

func (h *MeiliSearchHook) Fire(entry *logrus.Entry) error

Fire sends log entry to MeiliSearch

func (*MeiliSearchHook) Levels

func (h *MeiliSearchHook) Levels() []logrus.Level

Levels returns all log levels

type OpenSearchHook added in v0.1.4

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

OpenSearchHook represents an OpenSearch log hook

func NewOpenSearchHook added in v0.1.17

func NewOpenSearchHook(client *opensearch.Client, cfg *config.Config) *OpenSearchHook

NewOpenSearchHook creates new OpenSearch hook

func (*OpenSearchHook) Fire added in v0.1.4

func (h *OpenSearchHook) Fire(entry *logrus.Entry) error

Fire sends log entry to OpenSearch

func (*OpenSearchHook) Levels added in v0.1.4

func (h *OpenSearchHook) Levels() []logrus.Level

Levels returns all log levels

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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