log

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2024 License: MIT Imports: 7 Imported by: 3

README

go-logger

A flexible logging library built on top of zap with customizable log levels, structured logging, and context management.

Features

  • Log Levels: Supports standard and custom log levels including Trace, Debug, Info, Warn, Error, and Fatal.
  • Structured Logging: Easily add key-value pairs to log messages.
  • Contextual Logging: Attach loggers to context for efficient and structured logging throughout your application.
  • Custom Formatting: Includes options for JSON or console output, with customizable caller information formatting.
  • Trace-Level Handling: Provides custom handling for detailed trace logs.

Installation

To use go-logger in your project, import the package:

import "github.com/public-forge/go-logger"

Basic Usage

Creating a Logger

Create a new logger with JSON or console formatting and the desired log level:

config := &log.Config{
IsJson: true, // true for JSON output, false for console
Level:  "INFO", // log level: TRACE, DEBUG, INFO, WARNING, ERROR, FATAL
}

logger, err := log.NewLogger(config)
if err != nil {
panic("failed to initialize logger: " + err.Error())
}

// Set the logger as the default logger
log.SetDefaultLogger(logger)
Logging Messages

You can log messages at different levels:

logger.Info("This is an info message")
logger.Debugf("Debugging %s with id: %d", "test", 123)
logger.Errorw("Error occurred", "error", err)
logger.Fatal("Fatal error, application will terminate")
Structured Logging

Add context to logs using key-value pairs:

logger.WithField("userID", 1234).Info("User logged in")
logger.WithError(errors.New("file not found")).Error("Failed to open file")
Using Context with Logger

Attach a logger to a context to maintain structured logging in applications:

ctx := context.Background()
ctx = log.ToContext(ctx, logger)

// Retrieve logger from context
loggerFromCtx := log.FromContext(ctx)
loggerFromCtx.Info("Logging with context-attached logger")

Advanced Usage

Trace-Level Logging

go-logger provides a custom Trace level for detailed trace messages:

logger.Trace("Detailed trace message for debugging")
Skip Callers

Adjust the number of caller stack frames to skip for cleaner log outputs:

logger.SkipCallers(2).Info("Adjusted caller information")
Custom Formatting

Customize log formats for console output by changing the encoding and caller format:

config := &log.Config{
IsJson: false, // Use console output
Level:  "DEBUG",
}

// Additional customizations for console format
logger, err := log.NewLogger(config)

Log Level Conversion

Convert string log levels to LogLevel:

logLevel := log.Text2Level("INFO")
logger := log.newZap(false, logLevel)

Example Application

Below is an example of how to set up the logger and use it in a sample application:

package main

import (
	"context"
	"errors"
	"log"
)

func main() {
	// Set up logger
	config := &log.Config{
		IsJson: true,
		Level:  "DEBUG",
	}

	logger, err := log.NewLogger(config)
	if err != nil {
		log.Fatalf("failed to initialize logger: %v", err)
	}

	// Setting logger as default
	log.SetDefaultLogger(logger)

	// Example log messages
	logger.Info("Application started")
	logger.Debugf("Starting with configuration: %+v", config)

	// Using context for logger
	ctx := log.ToContext(context.Background(), logger)
	log.FromContext(ctx).Infow("Contextual log", "userID", 101)

	// Structured log with error context
	err = errors.New("sample error")
	logger.WithError(err).Error("An error occurred")

	logger.Fatal("Fatal error, exiting application")
}

Contributing

Feel free to open issues or submit pull requests to improve this library!

License

This library is open-source and available under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var LoggerConfig = Config{}

LoggerConfig holds the global logging configuration instance. This can be modified to set the desired logging settings across the application.

Functions

func SetDefaultContext

func SetDefaultContext(ctx context.Context)

SetDefaultContext sets a default context that may include logging configurations.

func SetDefaultLogger

func SetDefaultLogger(l Logger)

SetDefaultLogger sets a global Logger instance.

func ToContext

func ToContext(ctx context.Context, l Logger) context.Context

ToContext attaches a Logger to a given context for retrieval in other parts of the app.

func TraceLevelEncoder

func TraceLevelEncoder(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder)

TraceLevelEncoder formats trace-level messages distinctly for higher visibility.

Types

type Config

type Config struct {
	Level  string // Level defines the logging severity (e.g., "info", "debug").
	IsJson bool   // IsJson determines if the log output should be in JSON format.
}

Config defines the logging configuration structure. Level sets the logging level (e.g., "info", "debug", "error"). IsJson toggles between JSON format (true) or plain text format (false) for log output.

type LogLevel

type LogLevel uint8

LogLevel defines the severity of logs, from Panic (highest) to Trace (lowest).

const (
	// PanicLevel is the highest severity; logs and then panics.
	PanicLevel LogLevel = iota
	// FatalLevel logs and then exits the application.
	FatalLevel
	// ErrorLevel is for errors that require attention.
	ErrorLevel
	// WarnLevel is for non-critical issues that need monitoring.
	WarnLevel
	// InfoLevel is for general operational information.
	InfoLevel
	// DebugLevel is for detailed debugging information.
	DebugLevel
	// TraceLevel is for the most granular level of information.
	TraceLevel
)

func Text2Level

func Text2Level(level string) LogLevel

Text2Level converts a string log level to a LogLevel enum for structured logging.

type Logger

type Logger interface {
	// Info writes an informational message.
	Info(...interface{})
	// Infof writes a formatted informational message.
	Infof(string, ...interface{})
	// Infow writes an informational message with key-value pairs for context.
	Infow(string, ...interface{})
	// Warn writes a warning message.
	Warn(...interface{})
	// Warnf writes a formatted warning message.
	Warnf(string, ...interface{})
	// Warnw writes a warning message with key-value pairs for context.
	Warnw(string, ...interface{})
	// Error writes an error message.
	Error(...interface{})
	// Errorf writes a formatted error message.
	Errorf(string, ...interface{})
	// Errorw writes an error message with key-value pairs for context.
	Errorw(string, ...interface{})
	// Debug writes a debug message.
	Debug(...interface{})
	// Debugf writes a formatted debug message.
	Debugf(string, ...interface{})
	// Debugw writes a debug message with key-value pairs for context.
	Debugw(string, ...interface{})
	// Fatal writes a fatal message and typically triggers application exit.
	Fatal(...interface{})
	// Fatalf writes a formatted fatal message.
	Fatalf(string, ...interface{})
	// With adds fields for structured logging to all subsequent logs.
	With(f ...interface{}) Logger
	// Check returns true if the log level is enabled for the logger instance.
	Check(level LogLevel) bool
	// Print logs a general message without a specific severity.
	Print(v ...interface{})
	// WithField adds a single key-value pair to the Logger instance.
	WithField(key string, value interface{}) Logger
	// WithError attaches an error to the Logger instance for context.
	WithError(err error) Logger
	// SkipCallers skips a specified number of call stack frames for cleaner logs.
	SkipCallers(count int) Logger
}

Logger is an interface that defines logging methods with various log levels and formats.

func FromContext

func FromContext(ctx context.Context) Logger

FromContext retrieves a Logger from the provided context or falls back to a default logger.

func FromDefaultContext

func FromDefaultContext() Logger

FromDefaultContext returns a Logger instance based on defaultContext settings.

func GetDefaultLogger

func GetDefaultLogger() Logger

GetDefaultLogger returns the global Logger instance or initializes it based on LoggerConfig.

func NewLogger

func NewLogger(conf *Config) (Logger, error)

NewLogger creates a new Logger instance based on the provided configuration.

Jump to

Keyboard shortcuts

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