log

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2024 License: MIT Imports: 5 Imported by: 0

README

go-log

go-log is a structured logging package to provides a simple way to log messages in different levels. It is designed to be simple and easy to use.

Quick Start

go get -u github.com/rizanw/go-log

And you can drop this package in to replace your log very simply:

package main

import (
	"context"

	// import this log package
	log "github.com/rizanw/go-log"
)

func main() {
	var (
		appName = "go-app"
	)

	// use the log like this
	log.Infof(context.TODO(), nil, log.KV{"key": "value"}, "starting app %s", appName)
}

Configurable Log

You can also customize configuration for your log very simple:

package main

import (
	"context"
	// import this log package
	log "github.com/rizanw/go-log"
)

func main() {
	var (
		ctx = context.Background()
		err error
	)

	// customize configuration like this
	err = log.SetConfig(&log.Config{
		AppName:     "go-app",
		Environment: "development",
		WithCaller:  true,
	})
	if err != nil {
		// use the log like this
		log.Errorf(ctx, err, nil, "we got error with message: %s", err.Error())
	}
}

Note: SetConfig func is not thread safe, so call it once when initializing the app only.

Configuration

below is list of available configuration:

Key type Description
AppName string your application name
Environment string your application environment
Level log.Level minimum log level to be printed (default: DEBUG)
TimeFormat string desired time format (default: RFC3339)
WithCaller bool caller toggle to print which line is calling the log (default: false)
CallerSkip int which caller line wants to be print
WithStack bool toggle to print which stack trace error located (default: false)
StackLevel log.Level minimum log level for zap stack trace (default: ERROR)
StackMarshaller func(err error) interface{} function to get and log the stack trace for zerolog (default: zerolog/pkgerrors)
UseMultiWriters bool a toggle to print log into log file and log console (FilePath required)
FilePath string specify your output log files directories (default: no file)
UseJSON bool a toggle to format log as json (default: false)
UseColor bool a toggle to colorize your log console with zerolog
Engine log.Engine desired engine logger (default: zerolog)

note:

  • Keep in mind that taking a caller or stacktrace is eager and expensive (relatively speaking) and makes an additional allocation.
Engine Options

This pkg currently provides two engine (aka logger) to use:

if you confused to decide, you can read this article as reference.

Structured Log

by implementing structured logging, we can easily filter and search logs based on the key-value fields:

{
  "level": "info",
  "timestamp": "2024-07-23T14:52:00Z",
  "app": "golang-app",
  "env": "development",
  "request_id": "5825511e-196f-406b-baed-67a9da40a26a",
  "source": {
    "app": "ios",
    "version": "1.10.5"
  },
  "metadata": {
    "username": "hello",
    "password": "***"
  },
  "message": "[HTTP][Request]: POST /api/v1/login"
}

Hierarchical Log

this package provide 5 hierarchical levels based on the severity:

  • DEBUG - this log level is used to obtain diagnostic information that can be helpful for troubleshooting and debugging. These messages often contain verbose or fine-grained information about the inner workings of the system or application. When teams look for log data to filter out for cost savings, they often start with DEBUG logs.
  • INFO - this log level provide general information about the status of the system. This log level is useful for tracking an application's progress or operational milestones. For example, your application may create INFO logs upon application startup, when a user makes configuration changes, or when they successfully complete tasks.
  • WARN - this log level serves as a signal for potential issues that are not necessarily a critical error. For example, your system may generate a WARN log when it is short on resources. If WARN logs go unaddressed, they may lead to bigger issues in the future.
  • ERROR - this log level indicates significant problems that happened in the system. It usually denotes that an unexpected event or exception has occurred. This log level is crucial for identifying issues affecting user experience or overall functionality, so immediate attention is needed.
  • FATAL - this log level shows severe conditions that cause the system to terminate or operate in a significantly degraded state. These logs are used for serious problems, like crashes or conditions that threaten data integrity or application stability. FATAL logs often lead to service disruptions.

Usage

logging

you can log based on the severity hierarchy and each severity has 2 main functions:

  • unformatted, similar to Println in fmt package
// Debug
log.Debug(ctx, err, log.KV{}, "this is a debug log")
// Info
log.Info(ctx, err, log.KV{}, "this is an info log")
// Warn
log.Warn(ctx, err, log.KV{}, "this is a warning log")
// Error
log.Error(ctx, err, log.KV{}, "this is an error log")
// Fatal
log.Fatal(ctx, err, log.KV{}, "this is a fatal log")
  • formatted, similar to Printf in fmt package
// Debug
log.Debugf(ctx, err, log.KV{}, "this is a debug log: %s", err.Error())
// Info
log.Infof(ctx, err, log.KV{}, "this is an info log: %s", err.Error())
// Warn
log.Warnf(ctx, err, log.KV{}, "this is a warning log: %s", err.Error())
// Error
log.Errorf(ctx, err, log.KV{}, "this is an error log: %s", err.Error())
// Fatal
log.Fatalf(ctx, err, log.KV{}, "this is a fatal log: %s", err.Error())
context
// set request_id (generated) logging into context
ctx = log.SetRequestID(ctx)

// set request_id (by yours) logging into context
ctx = log.SetRequestID(ctx, requestID)
// set user_info logging into context
ctx = log.SetUserInfo(ctx, log.KV{"username": "hello"})
// set source logging into context
ctx = log.SetSource(ctx, log.KV{"app": source.App, "version": source.Version})
Additional Fields

Need more fields? coming soon!

Documentation

Index

Constants

View Source
const (
	KeyCtxRequestID = "request_id"
	KeyCtxUserInfo  = "user_info"
	KeyCtxSource    = "source"
)
View Source
const (
	DebugLevel = logger.DebugLevel
	InfoLevel  = logger.InfoLevel
	WarnLevel  = logger.WarnLevel
	ErrorLevel = logger.ErrorLevel
	FatalLevel = logger.FatalLevel
)

Level options

Variables

This section is empty.

Functions

func Debug

func Debug(ctx context.Context, err error, metadata KV, message string)

Debug prints log on debug level

func Debugf

func Debugf(ctx context.Context, err error, metadata KV, formatedMsg string, args ...interface{})

Debugf prints log on debug level like fmt.Printf

func Error

func Error(ctx context.Context, err error, metadata KV, message string)

Error prints log on error level

func Errorf

func Errorf(ctx context.Context, err error, metadata KV, formatedMsg string, args ...interface{})

Errorf prints log on error level like fmt.printf

func Fatal

func Fatal(ctx context.Context, err error, metadata KV, message string)

Fatal prints log on fatal level

func Fatalf

func Fatalf(ctx context.Context, err error, metadata KV, formatedMsg string, args ...interface{})

Fatalf prints log on fatal level like fmt.printf

func GetCtxRequestID

func GetCtxRequestID(ctx context.Context) string

GetCtxRequestID returns request_id from context

func GetCtxSource

func GetCtxSource(ctx context.Context) interface{}

func GetCtxUserInfo

func GetCtxUserInfo(ctx context.Context) interface{}

func Info

func Info(ctx context.Context, err error, metadata KV, message string)

Info prints log on info level

func Infof

func Infof(ctx context.Context, err error, metadata KV, formatedMsg string, args ...interface{})

Infof prints log on info level like fmt.Printf

func SetConfig

func SetConfig(config *Config) error

SetConfig is function to customize log configuration

func SetCtxRequestID

func SetCtxRequestID(ctx context.Context, requestID ...string) context.Context

SetCtxRequestID generates & sets request_id to context

func SetCtxSource

func SetCtxSource(ctx context.Context, source interface{}) context.Context

func SetCtxUserInfo

func SetCtxUserInfo(ctx context.Context, userInfo interface{}) context.Context

func Warn

func Warn(ctx context.Context, err error, metadata KV, message string)

Warn prints log on warn level

func Warnf

func Warnf(ctx context.Context, err error, metadata KV, formatedMsg string, args ...interface{})

Warnf prints log on warn level like fmt.Printf

Types

type Config

type Config struct {
	// AppName is your application name
	// it will be printed as `app` in log
	AppName string

	// Environment is your application environment running on
	// it will be printed as `env` in log
	// `dev` | `development` | `local` will mark your app under development env
	Environment string

	// Level is minimum log level to be printed (default: DEBUG)
	Level Level

	// TimeFormat is for log time format (default: RFC3339)
	TimeFormat string

	// WithCaller toggle to print which line is calling the log (default: false)
	WithCaller bool

	// CallerSkip is offset number for which caller line you wants to be print (default: 0)
	CallerSkip int

	// WithStack is a toggle to print which stack trace error located (default: false)
	WithStack bool

	// StackLevel is minimum log level for zap stack trace (default: ERROR)
	StackLevel *Level

	// StackMarshaller, function to get and log the stack trace for zerolog (default: `zerolog/pkgerrors`)
	StackMarshaller func(err error) interface{}

	// UseJSON is a toggle to format log as json (default: false)
	UseJSON bool

	// UseColor is a toggle to colorize your log console
	// note: it only works using `zerolog` engine and under `development` environment
	UseColor bool

	// UseMultiWriters is a toggle to print log into log file and log console
	// note: FilePath must be filled
	UseMultiWriters bool

	// FilePath a file path to write the log as a file
	// note: if you fill the file path, your console log will be empty.
	FilePath string

	// Engine is logger to be used
	Engine Engine
}

Config for Log configuration

type Engine

type Engine = logger.Engine

Engine logger

const (
	Zap     Engine = logger.EngineZap
	Zerolog Engine = logger.EngineZerolog
)

Engine options

type KV

type KV map[string]interface{}

type Level

type Level = logger.Level

Level of log

type Logger

type Logger = logger.ILogger

Logger interface

func NewLogger

func NewLogger(config logger.Config, engine logger.Engine) (Logger, error)

NewLogger creates a logger instance based on selected logger engine

Directories

Path Synopsis
zap

Jump to

Keyboard shortcuts

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