log

package
v0.0.0-...-83d3ec8 Latest Latest
Warning

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

Go to latest
Published: May 19, 2025 License: Apache-2.0 Imports: 12 Imported by: 0

README

Log Package

The log package provides structured logging capabilities for Moov applications.

Usage

Basic Logging
import "github.com/anguishedcha/base/log"

// Create a new logger
logger := log.NewDefaultLogger()

// Log a message with different levels
logger.Info().Log("Application started")
logger.Debug().Log("Debug information")
logger.Warn().Log("Warning message")
logger.Error().Log("Error occurred")

// Log with key-value pairs
logger.Info().Set("request_id", log.String("12345")).Log("Processing request")

// Log formatted messages
logger.Infof("Processing request %s", "12345")

// Log errors
err := someFunction()
if err != nil {
    logger.LogError(err)
}
Using Fields
import "github.com/anguishedcha/base/log"

// Create a map of fields
fields := log.Fields{
    "request_id": log.String("12345"),
    "user_id":    log.Int(42),
    "timestamp":  log.Time(time.Now()),
}

// Log with fields
logger.With(fields).Info().Log("Request processed")
Using StructContext

The StructContext function allows you to log struct fields automatically by using tags.

import "github.com/anguishedcha/base/log"

// Define a struct with log tags
type User struct {
    ID       int    `log:"id"`
    Username string `log:"username"`
    Email    string `log:"email,omitempty"` // won't be logged if empty
    Address  Address `log:"address"` // nested struct must have log tag
    Hidden   string // no log tag, won't be logged
}

type Address struct {
    Street  string `log:"street"`
    City    string `log:"city"`
    Country string `log:"country"`
}

// Create a user
user := User{
    ID:       1,
    Username: "johndoe",
    Email:    "john@example.com",
    Address: Address{
        Street:  "123 Main St",
        City:    "New York",
        Country: "USA",
    },
    Hidden: "secret",
}

// Log with struct context
logger.With(log.StructContext(user)).Info().Log("User logged in")

// Log with struct context and prefix
logger.With(log.StructContext(user, log.WithPrefix("user"))).Info().Log("User details")

// Using custom tag other than "log"
type Product struct {
    ID    int     `otel:"product_id"`
    Name  string  `otel:"product_name"`
    Price float64 `otel:"price,omitempty"`
}

product := Product{
    ID:    42,
    Name:  "Widget",
    Price: 19.99,
}

// Use otel tags instead of log tags
logger.With(log.StructContext(product, log.WithTag("otel"))).Info().Log("Product details")

The above will produce log entries with the following fields:

  • id=1
  • username=johndoe
  • email=john@example.com
  • address.street=123 Main St
  • address.city=New York
  • address.country=USA

With the prefix option, the fields will be:

  • user.id=1
  • user.username=johndoe
  • user.email=john@example.com
  • user.address.street=123 Main St
  • user.address.city=New York
  • user.address.country=USA

With the custom tag option, the fields will be extracted from the tag you specify (such as otel):

  • product_id=42
  • product_name=Widget
  • price=19.99

Note that nested structs or pointers to structs must have the specified tag to be included in the context.

Features

  • Structured logging with key-value pairs
  • Multiple log levels (Debug, Info, Warn, Error, Fatal)
  • JSON and LogFmt output formats
  • Context-based logging
  • Automatic struct field logging with StructContext
  • Support for various value types (string, int, float, bool, time, etc.)

Configuration

The default logger format is determined by the MOOV_LOG_FORMAT environment variable:

  • json: JSON format
  • logfmt: LogFmt format (default)
  • nop or noop: No-op logger that discards all logs

Documentation

Index

Constants

View Source
const Debug = Level("debug")

Info is sets level=info in the log output

View Source
const Error = Level("error")

Error sets level=error in the log output

View Source
const Fatal = Level("fatal")

Fatal sets level=fatal in the log output

View Source
const Info = Level("info")

Info is sets level=info in the log output

View Source
const StackTrace = st("stacktrace")
View Source
const Warn = Level("warn")

Info is sets level=warn in the log output

Variables

This section is empty.

Functions

func NewBufferLogger

func NewBufferLogger() (*BufferedLogger, Logger)

Types

type BufferedLogger

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

func (*BufferedLogger) Reset

func (bl *BufferedLogger) Reset()

func (*BufferedLogger) String

func (bl *BufferedLogger) String() string

func (*BufferedLogger) Write

func (bl *BufferedLogger) Write(p []byte) (n int, err error)

type Context

type Context interface {
	Context() map[string]Valuer
}

func StructContext

func StructContext(v interface{}, opts ...StructContextOption) Context

StructContext creates a Context from a struct, extracting fields tagged with `log` It supports nested structs and respects omitempty directive

type Fields

type Fields map[string]Valuer

func (Fields) Context

func (f Fields) Context() map[string]Valuer

type Level

type Level string

Level just wraps a string to be able to add Context specific to log levels

func (Level) Context

func (l Level) Context() map[string]Valuer

Context returns the map that states that key value of `level={{l}}`

type LoggedError

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

func (LoggedError) Err

func (l LoggedError) Err() error

func (LoggedError) Nil

func (l LoggedError) Nil() error

type Logger

type Logger interface {
	Set(key string, value Valuer) Logger
	With(ctxs ...Context) Logger
	Details() map[string]interface{}

	Debug() Logger
	Info() Logger
	Warn() Logger
	Error() Logger
	Fatal() Logger

	Log(message string)
	Logf(format string, args ...interface{})
	Send()

	LogError(error error) LoggedError
	LogErrorf(format string, args ...interface{}) LoggedError
}

func NewDefaultLogger

func NewDefaultLogger() Logger

func NewJSONLogger

func NewJSONLogger() Logger

func NewLogFmtLogger

func NewLogFmtLogger() Logger

func NewLogger

func NewLogger(writer log.Logger) Logger

func NewNopLogger

func NewNopLogger() Logger

func NewTestLogger

func NewTestLogger() Logger

type StructContextOption

type StructContextOption func(*structContext)

StructContextOption defines options for StructContext

func WithPrefix

func WithPrefix(prefix string) StructContextOption

WithPrefix adds a prefix to all struct field names

func WithTag

func WithTag(tag string) StructContextOption

WithTag adds a custom tag to look for in struct fields

type Valuer

type Valuer interface {
	// contains filtered or unexported methods
}

Valuer is an interface to deal with typing problems of just having an interface{} as the acceptable parameters Go-kit logging has a failure case if you attempt to throw any values into it. This is a way to guard our developers from having to worry about error cases of the lower logging framework.

func Bool

func Bool(b bool) Valuer

func ByteBase64

func ByteBase64(b []byte) Valuer

func ByteString

func ByteString(b []byte) Valuer

func Float32

func Float32(f float32) Valuer

func Float64

func Float64(f float64) Valuer

func Int

func Int(i int) Valuer

func Int64

func Int64(i int64) Valuer

func Int64OrNil

func Int64OrNil(i *int64) Valuer

func String

func String(s string) Valuer

func StringOrNil

func StringOrNil(s *string) Valuer

func Stringer

func Stringer(s fmt.Stringer) Valuer

func Strings

func Strings(vals []string) Valuer

func Time

func Time(t time.Time) Valuer

func TimeDuration

func TimeDuration(d time.Duration) Valuer

func TimeFormatted

func TimeFormatted(t time.Time, format string) Valuer

func TimeOrNil

func TimeOrNil(t *time.Time) Valuer

func Uint32

func Uint32(i uint32) Valuer

func Uint64

func Uint64(i uint64) Valuer

Jump to

Keyboard shortcuts

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