• Stars
    star
    292
  • Rank 142,126 (Top 3 %)
  • Language
    Go
  • License
    MIT License
  • Created over 8 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ“— Simple, configurable and scalable Structured Logging for Go.

log

Project status Test Coverage Status Go Report Card GoDoc License

Log is a simple, highly configurable, Structured Logging library

Why another logging library?

There's a lot of great stuff out there, but this library contains a number of unique features noted below using *.

Features

  • Logger is simple, only logic to create the log entry and send it off to the handlers, they take it from there.
  • Handlers are simple to write + easy to register + easy to remove
  • *Ability to specify which log levels get sent to each handler
  • *Handlers & Log Levels are configurable at runtime.
  • *WithError automatically extracts and adds file, line and package in error output.
  • *Convenient context helpers GetContext & SetContext
  • *Works with go-playground/errors extracting wrapped errors, types and tags when used with the WithError interface. This is the default but configurable to support more or other error libraries using SetWithErrorFn.
  • *Default logger for quick prototyping and cli applications. It is automatically removed when you register one of your own.

Installation

Use go get

go get github.com/go-playground/log/v8@latest

Usage

import the log package.

package main

import (
	"io"
	stdlog "log"

	"github.com/go-playground/errors/v5"
	"github.com/go-playground/log/v8"
)

func main() {
	log.RedirectGoStdLog(true)

	// Trace
	defer log.WithTrace().Info("time to run")

	log.Debug("debug")
	log.Info("info")
	log.Notice("notice")
	log.Warn("warn")
	log.Error("error")
	// log.Panic("panic") // this will panic
	log.Alert("alert")
	// log.Fatal("fatal") // this will call os.Exit(1)

	err := errors.New("this is the inner error").AddTags(errors.T("inner", "tag"))
	err = errors.Wrap(err, "this is the wrapping error").AddTags(errors.T("outer", "tag"))

	// logging with fields can be used with any of the above
	log.WithError(err).WithFields(log.F("key", "value")).Info("test info")

	// log unwrapped error
	log.WithError(io.EOF).Error("unwrapped error")

	// predefined global fields
	log.WithDefaultFields(log.Fields{
		log.F("program", "test"),
		log.F("version", "0.1.3"),
	}...)

	log.WithField("key", "value").Info("testing default fields")

	// or request scoped default fields
	logger := log.WithFields(
		log.F("request", "req"),
		log.F("scoped", "sco"),
	)

	logger.WithField("key", "value").Info("test")

	stdlog.Println("This was redirected from Go STD output!")
	log.RedirectGoStdLog(false)
	stdlog.Println("This was NOT redirected from Go STD output!")
}

Adding your own Handler

package main

import (
	"bytes"
	"fmt"

	"github.com/go-playground/log/v8"
)

// CustomHandler is your custom handler
type CustomHandler struct {
	// whatever properties you need
}

// Log accepts log entries to be processed
func (c *CustomHandler) Log(e log.Entry) {

	// below prints to os.Stderr but could marshal to JSON
	// and send to central logging server
	//																						       ---------
	// 				                                                                 |----------> | console |
	//                                                                               |             ---------
	// i.e. -----------------               -----------------     Unmarshal    -------------       --------
	//     | app log handler | -- json --> | central log app | --    to    -> | log handler | --> | syslog |
	//      -----------------               -----------------       Entry      -------------       --------
	//      																         |             ---------
	//                                  									         |----------> | DataDog |
	//          																	        	   ---------
	b := new(bytes.Buffer)
	b.Reset()
	b.WriteString(e.Message)

	for _, f := range e.Fields {
		_, _ = fmt.Fprintf(b, " %s=%v", f.Key, f.Value)
	}
	fmt.Println(b.String())
}

func main() {

	cLog := new(CustomHandler)
	log.AddHandler(cLog, log.AllLevels...)

	// Trace
	defer log.WithTrace().Info("took this long")

	log.Debug("debug")
	log.Info("info")
	log.Notice("notice")
	log.Warn("warn")
	log.Error("error")
	// log.Panic("panic") // this will panic
	log.Alert("alert")
	// log.Fatal("fatal") // this will call os.Exit(1)

	// logging with fields can be used with any of the above
	log.WithField("key", "value").Info("test info")
}

Go 1.21+ slog compatibility

There is a compatibility layer for slog, which allows redirecting slog to this logger and ability to output to an slog.Handler+.

type Definition
Handler This example demonstrates how to redirect the std log and slog to this logger by using it as an slog.Handler.
Redirect This example demonstrates how to redirect the std log and slog to this logger and output back out to any slog.Handler, as well as any other handler(s) registered with this logger.
Log Level Definitions
---------------------

| Level  | Description                                                                                                                                                                                               |
|--------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Debug  | Info useful to developers for debugging the application, not useful during normal operations.                                                                                                             |
| Info   | Normal operational messages which may be harvested for reporting, measuring throughput, etc. no action required.                                                                                          |
| Notice | Normal but significant condition. Events that are unusual but not error conditions eg. might be summarized in an email to developers or admins to spot potential problems - no immediate action required. |
| Warn   | Warning messages, not an error, but indication that an error will occur if action is not taken, e.g. file system 85% full. Each item must be resolved within a given time.                                |
| Error  | Non-urgent failures, these should be relayed to developers or admins; each item must be resolved within a given time.                                                                                     |
| Panic  | A "panic" condition usually affecting multiple apps/servers/sites. At this level it would usually notify all tech staff on call.                                                                          |
| Alert  | Action must be taken immediately. Should be corrected immediately, therefore notify staff who can fix the problem. An example would be the loss of a primary ISP connection.                              |
| Fatal  | Should be corrected immediately, but indicates failure in a primary system, an example is a loss of a backup ISP connection. ( same as SYSLOG CRITICAL )                                                  |

Handlers
-------------
Pull requests for new handlers are welcome when they don't pull in dependencies, it is preferred to have a dedicated package in this case.

| Handler | Description                                                                                                                              | Docs                                                                                                                                                              |
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| json    | Allows for log messages to be sent to any wrtier in json format.                                                                         | [![GoDoc](https://godoc.org/github.com/go-playground/log/handlers/json?status.svg)](https://godoc.org/github.com/go-playground/log/handlers/json)                 |

Package Versioning
----------
This package strictly adheres to semantic versioning guidelines.

More Repositories

1

validator

πŸ’―Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
Go
16,425
star
2

webhooks

🎣 Webhook receiver for GitHub, Bitbucket, GitLab, Gogs
Go
949
star
3

form

πŸš‚ Decodes url.Values into Go value(s) and Encodes Go value(s) into url.Values. Dual Array and Full map support.
Go
750
star
4

pool

🚀 a limited consumer goroutine or unlimited goroutine pool for easier goroutine handling and cancellation
Go
724
star
5

lars

🚨 Is a lightweight, fast and extensible zero allocation HTTP router for Go used to create customizable frameworks.
Go
386
star
6

universal-translator

πŸ’¬ i18n Translator for Go/Golang using CLDR data + pluralization rules
Go
375
star
7

locales

🌎 a set of locales generated from the CLDR Project which can be used independently or within an i18n package; these were built for use with, but not exclusive to https://github.com/go-playground/universal-translator
Go
267
star
8

mold

βœ‚οΈ Is a general library to help modify or set data within data structures and other objects.
Go
225
star
9

stats

πŸ“ˆ Monitors Go MemStats + System stats such as Memory, Swap and CPU and sends via UDP anywhere you want for logging etc...
Go
170
star
10

pure

🚱 Is a lightweight HTTP router that sticks to the std "net/http" implementation
Go
149
star
11

overalls

πŸ‘–Multi-Package go project coverprofile for tools like goveralls
Go
114
star
12

statics

πŸ“ Embeds static resources into go files for single binary compilation + works with http.FileSystem + symlinks
Go
68
star
13

colors

🎨 Go color manipulation, conversion and printing library/utility
Go
67
star
14

assert

❗Basic Assertion Library used along side native go testing, with building blocks for custom assertions
Go
62
star
15

errors

πŸ’₯Error Context, Stack Trace, Types and Tags for full error handling and logging.
Go
61
star
16

kms

πŸ”ͺ Is a library that aids in graceful shutdown of a process/application
Go
47
star
17

pkg

⭐ pkg extends the core go packages with missing or additional functionality built in. All packages correspond to the std go package name with an additional suffix of `ext` to avoid naming conflicts.
Go
42
star
18

tz

Timezone Country and Zone data generated from timezonedb.com
Go
30
star
19

generate

πŸƒruns go generate recursively on a specified path or environment variable and can filter by regex
Go
30
star
20

justdoit

simple auto-compile daemon that just works
Go
19
star
21

spoon

library + program to help making zero downtime, self-upgrading programs and servers.
Go
16
star
22

retry

πŸ”„ Retry provides a set of standardized common components and abstracts away some code that normally is duplicated
Go
16
star
23

ansi

⬛ ansi contains a bunch of constants and possibly additional terminal related functionality in the future.
Go
14
star
24

sensitive

provides base types who's values should never be seen by the human eye, but still used for configuration.
Go
14
star
25

ksql

a JSON data expression lexer, parser, cli and library
Go
13
star
26

backoff

:bowtie: Backoff uses an exponential backoff algorithm to backoff between retries with optional auto-tuning functionality.
Go
12
star
27

cache

Contains multiple in-memory cache implementations including LRU & LFU
Go
11
star
28

assets

Asset Pipeline for Go HTML applications
Go
8
star
29

ws

πŸ™Œ ws creates a hub for WebSocket connections and abstracts away allot of the boilerplate code for managing connections using Gorilla WebSocket
Go
8
star
30

itertools

Go Iteration tools with a rusty flavour
Go
7
star
31

livereload

πŸ” is an asset live-reload library that allows easy registration of path & file change monitoring and notifications for https://github.com/livereload/livereload-js
JavaScript
6
star
32

relay-client-go

This package is a Go client for the Relay Job Runner https://github.com/rust-playground/relay-rs
Go
5
star
33

backoff-sys

Bare building blocks for backing off and can be used to build more complex backoff packages
Go
4
star
34

mongostore

πŸ”‘ Gorilla's session store implementation using MongoDB
Go
4
star
35

bundler

Generic Bundler to concatenate any type of files using a custom left and right delimiter, i.e. css or js files
Go
4
star
36

wave

〰️ Package wave is a thin helper layer on top of Go's net/rpc
Go
1
star