Categorygithub.com/rizanw/go-log
modulepackage
0.3.0
Repository: https://github.com/rizanw/go-log.git
Documentation: pkg.go.dev

# 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:

KeytypeDescription
AppNamestringyour application name
Environmentstringyour application environment
Levellog.Levelminimum log level to be printed (default: DEBUG)
TimeFormatstringdesired time format (default: RFC3339)
WithCallerboolcaller toggle to print which line is calling the log (default: false)
CallerSkipintwhich caller line wants to be print
WithStackbooltoggle to print which stack trace error located (default: false)
StackLevellog.Levelminimum log level for zap stack trace (default: ERROR)
StackMarshallerfunc(err error) interface{}function to get and log the stack trace for zerolog (default: zerolog/pkgerrors)
UseMultiWritersboola toggle to print log into log file and log console (FilePath required)
FilePathstringspecify your output log files directories (default: no file)
UseJSONboola toggle to format log as json (default: false)
UseColorboola toggle to colorize your log console with zerolog
Enginelog.Enginedesired 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!

# Packages

No description provided by the author
No description provided by the author

# Functions

Debug prints log on debug level.
Debugf prints log on debug level like fmt.Printf.
Error prints log on error level.
Errorf prints log on error level like fmt.printf.
Fatal prints log on fatal level.
Fatalf prints log on fatal level like fmt.printf.
GetCtxRequestID returns request_id from context.
No description provided by the author
No description provided by the author
Info prints log on info level.
Infof prints log on info level like fmt.Printf.
NewLogger creates a logger instance based on selected logger engine.
SetConfig is function to customize log configuration.
SetCtxRequestID generates & sets request_id to context.
No description provided by the author
No description provided by the author
Warn prints log on warn level.
Warnf prints log on warn level like fmt.Printf.

# Constants

Level options.
Level options.
Level options.
Level options.
No description provided by the author
No description provided by the author
No description provided by the author
Level options.
Engine options.
Engine options.

# Structs

Config for Log configuration.

# Type aliases

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author