log

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2025 License: GPL-3.0 Imports: 8 Imported by: 0

Documentation

Overview

Example (AdditionalFields)

Example_additionalFields demonstrates using additional fields in config

package main

import (
	"github.com/ducminhgd/gao/log"
)

func main() {
	logger, _ := log.New(log.Config{
		Kind:        log.KindZap,
		Level:       log.LevelInfo,
		ServiceName: "my-service",
		AdditionalFields: []log.Field{
			{Key: "region", Value: "us-east-1"},
			{Key: "availability_zone", Value: "us-east-1a"},
			{Key: "instance_id", Value: "i-1234567890abcdef0"},
		},
	})

	// All logs will include the additional fields
	logger.Info("Server started")
}
Example (ConsoleFormat)

Example_consoleFormat demonstrates using console format for development

package main

import (
	"github.com/ducminhgd/gao/log"
)

func main() {
	logger, _ := log.New(log.Config{
		Kind:   log.KindZap,
		Level:  log.LevelInfo,
		Format: log.FormatConsole,
	})

	logger.Info("Console formatted output", log.Field{Key: "readable", Value: true})
}
Example (CustomContextExtractor)

Example_customContextExtractor demonstrates using a custom context extractor

package main

import (
	"context"

	"github.com/ducminhgd/gao/log"
)

func main() {
	customExtractor := func(ctx context.Context) []log.Field {
		var fields []log.Field

		// Extract custom fields from context
		if orgID := ctx.Value("org_id"); orgID != nil {
			fields = append(fields, log.Field{Key: "org_id", Value: orgID})
		}
		if tenantID := ctx.Value("tenant_id"); tenantID != nil {
			fields = append(fields, log.Field{Key: "tenant_id", Value: tenantID})
		}

		return fields
	}

	logger, _ := log.New(log.Config{
		Kind:             log.KindZap,
		Level:            log.LevelInfo,
		ContextExtractor: customExtractor,
	})

	ctx := context.WithValue(context.Background(), "org_id", "org-789")
	ctx = context.WithValue(ctx, "tenant_id", "tenant-456")

	logger.WithContext(ctx).Info("Multi-tenant operation")
}
Example (DifferentLogLevels)

Example_differentLogLevels demonstrates using different log levels

package main

import (
	"github.com/ducminhgd/gao/log"
)

func main() {
	logger, _ := log.New(log.Config{
		Kind:  log.KindZap,
		Level: log.LevelDebug,
	})

	logger.Debug("Detailed debugging information", log.Field{Key: "variable", Value: "value"})
	logger.Info("Informational message")
	logger.Warn("Warning: resource usage high", log.Field{Key: "cpu_percent", Value: 85})
	logger.Error("Error processing request", log.Field{Key: "error", Value: "timeout"})
}
Example (GlobalLogger)

Example_globalLogger demonstrates using the global logger functions

package main

import (
	"github.com/ducminhgd/gao/log"
)

func main() {
	// Create and set the global logger
	_, err := log.New(log.Config{
		Kind:  log.KindZap,
		Level: log.LevelInfo,
	})
	if err != nil {
		panic(err)
	}

	// Use global functions
	log.Info("Application started")
	log.Info("User action", log.Field{Key: "action", Value: "login"})
	log.Error("An error occurred", log.Field{Key: "error", Value: "database connection failed"})
}
Example (JsonFormat)

Example_jsonFormat demonstrates using JSON format for production

package main

import (
	"github.com/ducminhgd/gao/log"
)

func main() {
	logger, _ := log.New(log.Config{
		Kind:   log.KindSlog,
		Level:  log.LevelInfo,
		Format: log.FormatJSON,
	})

	logger.Info("JSON formatted output", log.Field{Key: "structured", Value: true})
}
Example (StructuredLogging)

Example_structuredLogging demonstrates structured logging with multiple fields

package main

import (
	"github.com/ducminhgd/gao/log"
)

func main() {
	logger, _ := log.New(log.SimpleConfig())

	logger.Info("User registered",
		log.Field{Key: "user_id", Value: "user-123"},
		log.Field{Key: "email", Value: "user@example.com"},
		log.Field{Key: "registration_method", Value: "oauth"},
		log.Field{Key: "provider", Value: "google"},
	)

	logger.Error("Database query failed",
		log.Field{Key: "query", Value: "SELECT * FROM users WHERE id = ?"},
		log.Field{Key: "error", Value: "connection timeout"},
		log.Field{Key: "duration_ms", Value: 5000},
	)
}

Index

Examples

Constants

View Source
const (
	KindZap  = "zap"
	KindSlog = "slog"
)
View Source
const (
	LevelDebug = "debug"
	LevelInfo  = "info"
	LevelWarn  = "warn"
	LevelError = "error"
	LevelFatal = "fatal"
)
View Source
const (
	FormatJSON    = "json"
	FormatConsole = "console"
)

Variables

View Source
var (
	// DefaultSlogLogger is a default slog.Logger instance for backward compatibility
	DefaultSlogLogger = slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		AddSource: true,
	}))
)

Functions

func ConvertSlogLevel

func ConvertSlogLevel(l string) slog.Level

func Debug added in v0.3.0

func Debug(msg string, fields ...Field)

func Error added in v0.3.0

func Error(msg string, fields ...Field)

func Fatal added in v0.3.0

func Fatal(msg string, fields ...Field)

func Info added in v0.3.0

func Info(msg string, fields ...Field)

func NewGORMLogger

func NewGORMLogger(loglevel string) *gormslog.Logger

func SetStd added in v0.3.0

func SetStd(l Logger)

func Warn added in v0.3.0

func Warn(msg string, fields ...Field)

Types

type Config added in v0.3.0

type Config struct {
	Kind   string // KindZap, KindSlog
	Level  string // LevelDebug, LevelInfo, LevelWarn, LevelError, LevelFatal
	Format string // FormatJSON or FormatConsole

	Development      bool
	ServiceName      string
	ServiceVersion   string
	Environment      string
	EnableCaller     bool
	EnableStacktrace bool
	AdditionalFields []Field

	ContextExtractor ContextExtractor
}

func DefaultConfig added in v0.3.0

func DefaultConfig() Config

DefaultConfig returns the default production configuration

Example

ExampleDefaultConfig demonstrates using default production config

package main

import (
	"github.com/ducminhgd/gao/log"
)

func main() {
	logger, err := log.New(log.DefaultConfig())
	if err != nil {
		panic(err)
	}

	logger.Info("Production logger initialized")
}

func DevelopmentConfig added in v0.3.0

func DevelopmentConfig() Config

DevelopmentConfig returns a configuration suitable for development

Example

ExampleDevelopmentConfig demonstrates using development config

package main

import (
	"github.com/ducminhgd/gao/log"
)

func main() {
	logger, err := log.New(log.DevelopmentConfig())
	if err != nil {
		panic(err)
	}

	logger.Debug("Development mode enabled")
}

func SimpleConfig added in v0.3.0

func SimpleConfig() Config

SimpleConfig returns a minimal configuration

type ContextExtractor added in v0.3.0

type ContextExtractor func(ctx context.Context) []Field

ContextExtractor extracts fields from a context

func DefaultContextExtractor added in v0.3.0

func DefaultContextExtractor() ContextExtractor

DefaultContextExtractor returns a context extractor that looks for common trace/request IDs

type Field added in v0.3.0

type Field struct {
	Key   string
	Value any
}

Field is a key-value pair for structured logging

type Logger

type Logger interface {
	Debug(msg string, fields ...Field)
	Info(msg string, fields ...Field)
	Warn(msg string, fields ...Field)
	Error(msg string, fields ...Field)
	Fatal(msg string, fields ...Field)

	// WithFields returns a new logger with preset fields
	WithFields(fields ...Field) Logger

	// WithContext extracts correlation IDs from context (trace_id, request_id, etc.)
	WithContext(ctx context.Context) Logger
}

Logger is the main interface for structured logging

func New added in v0.3.0

func New(config Config) (Logger, error)

New creates a logger. First logger becomes the global default.

Example (Development)

ExampleNew_development demonstrates creating a development logger

package main

import (
	"github.com/ducminhgd/gao/log"
)

func main() {
	logger, err := log.New(log.DevelopmentConfig())
	if err != nil {
		panic(err)
	}

	logger.Debug("Debug information")
	logger.Info("Application started")
}
Example (SlogLogger)

ExampleNew_slogLogger demonstrates creating a slog logger

package main

import (
	"github.com/ducminhgd/gao/log"
)

func main() {
	logger, err := log.New(log.Config{
		Kind:   log.KindSlog,
		Level:  log.LevelInfo,
		Format: log.FormatJSON,
	})
	if err != nil {
		panic(err)
	}

	logger.Info("Application started")
	logger.Info("User logged in", log.Field{Key: "user_id", Value: "12345"})
}
Example (WithServiceMetadata)

ExampleNew_withServiceMetadata demonstrates creating a logger with service metadata

package main

import (
	"github.com/ducminhgd/gao/log"
)

func main() {
	logger, err := log.New(log.Config{
		Kind:           log.KindZap,
		Level:          log.LevelInfo,
		Format:         log.FormatJSON,
		ServiceName:    "my-api",
		ServiceVersion: "1.0.0",
		Environment:    "production",
	})
	if err != nil {
		panic(err)
	}

	logger.Info("Service initialized")
}
Example (ZapLogger)

ExampleNew_zapLogger demonstrates creating a Zap logger

package main

import (
	"github.com/ducminhgd/gao/log"
)

func main() {
	logger, err := log.New(log.Config{
		Kind:   log.KindZap,
		Level:  log.LevelInfo,
		Format: log.FormatJSON,
	})
	if err != nil {
		panic(err)
	}

	logger.Info("Application started")
	logger.Info("User logged in", log.Field{Key: "user_id", Value: "12345"})
}

func WithContext added in v0.3.0

func WithContext(ctx context.Context) Logger

func WithFields added in v0.3.0

func WithFields(fields ...Field) Logger

Jump to

Keyboard shortcuts

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