log

package module
v1.1.8 Latest Latest
Warning

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

Go to latest
Published: May 13, 2020 License: MIT Imports: 8 Imported by: 0

README

log

It is a simple structured logging package for Go.

Features

  • easy and configurable
  • built-in some handlers
  • allow to use different level for each handler
  • goroutine safety
  • allow to add default fields to every log. ( ex. You maybe want to add app_id per each app or env per each environment)
  • colored text for console handler (linux, mac, and windows are supported)
  • trace time
  • work with error interface
  • Go standard context is supported

Handlers

  • console
  • gelf (graylog)
  • memory (unit test)
  • discard (benchmark)

Installation

Use go get

go get -u gitlab.silkrode.com.tw/golang/log

Example

package main

import (
	"errors"

	"gitlab.silkrode.com.tw/golang/log"
	"gitlab.silkrode.com.tw/golang/log/handlers/console"
)

func main() {
	// use console handler to log all level logs
	clog := console.New()
	log.RegisterHandler(clog, log.AllLevels...)

	// optional: allow handlers to clear all buffer
	defer log.Flush()

	// use withDefaultFields to add fields to every logs
	log.WithDefaultFields(
		log.Fields{
			"app_id": "santa",
			"env":    "dev",
		},
	)

	// use trace to get how long it takes
	defer log.Trace("time to run").Stop()

	// print message use DEBUG level
	log.Debug("hello world")

	// log information with custom fileds
	fields := log.Fields{
		"city": "keelung",
	}
	log.WithFields(fields).Infof("more info")

	// log error struct and print error message
	err := errors.New("something bad happened")
	log.WithError(err).Error("oops...")
}

Output

Benchmarks

Run on MacBook Pro 15-inch 2018 using go version go1.13.5 windows 10 OS

go test -bench=. -benchmem -run=^bb -v

goos: windows
goarch: amd64
pkg: github.com/jasonsoft/log
BenchmarkSmall-12       13483690                82.6 ns/op             0 B/op          0 allocs/op
BenchmarkMedium-12       2489635               605 ns/op             336 B/op          2 allocs/op
BenchmarkLarge-12         479955              2802 ns/op            2183 B/op          9 allocs/op
PASS
ok      github.com/jasonsoft/log        4.604s

Documentation

Index

Constants

This section is empty.

Variables

AllLevels is an array of all log levels, for easier registering of all levels to a handler

Functions

func Debug

func Debug(msg string)

Debug level formatted message.

func Debugf

func Debugf(msg string, v ...interface{})

Debugf level formatted message.

func Error

func Error(msg string)

Error level formatted message

func Errorf

func Errorf(msg string, v ...interface{})

Errorf level formatted message

func Fatal

func Fatal(msg string)

Fatal level formatted message, followed by an exit.

func Fatalf

func Fatalf(msg string, v ...interface{})

Fatalf level formatted message, followed by an exit.

func Flush

func Flush()

Flush clear all handler's buffer

func Info

func Info(msg string)

Info level formatted message.

func Infof

func Infof(msg string, v ...interface{})

Infof level formatted message.

func NewContext

func NewContext(ctx context.Context, e Entry) context.Context

NewContext return a new context with a logger value

func Panic

func Panic(msg string)

Panic level formatted message

func Panicf

func Panicf(msg string, v ...interface{})

Panicf level formatted message

func RegisterHandler

func RegisterHandler(handler Handler, levels ...Level)

RegisterHandler adds a new Log Handler and specifies what log levels the handler will be passed log entries for

func Warn

func Warn(msg string)

Warn level formatted message.

func Warnf

func Warnf(msg string, v ...interface{})

Warnf level formatted message.

func WithDefaultFields

func WithDefaultFields(fields Fields)

WithDefaultFields adds fields to every entry instance

Types

type Entry

type Entry struct {
	Level     Level     `json:"level"`
	Message   string    `json:"message"`
	Timestamp time.Time `json:"timestamp"`
	Fields    Fields    `json:"fields"` // single map; easy to use for handlers
	// contains filtered or unexported fields
}

Entry defines a single log entry

func FromContext

func FromContext(ctx context.Context) Entry

FromContext return a logger from the context

func Trace

func Trace(msg string) Entry

Trace returns a new entry with a Stop method to fire off a corresponding completion log, useful with defer.

func WithError

func WithError(err error) Entry

WithError returns a new entry with the "error" set to `err`.

func WithField

func WithField(key string, value interface{}) Entry

WithField returns a new entry with the `key` and `value` set.

func WithFields

func WithFields(fields Fields) Entry

WithFields returns a log Entry with fields set

func (Entry) Debug

func (e Entry) Debug(msg string)

Debug level message.

func (Entry) Debugf

func (e Entry) Debugf(msg string, v ...interface{})

Debugf level message.

func (Entry) Error

func (e Entry) Error(msg string)

Error level message.

func (Entry) Errorf

func (e Entry) Errorf(msg string, v ...interface{})

Errorf level message.

func (Entry) Fatal

func (e Entry) Fatal(msg string)

Fatal level message.

func (Entry) Fatalf

func (e Entry) Fatalf(msg string, v ...interface{})

Fatalf level message.

func (Entry) Info

func (e Entry) Info(msg string)

Info level message.

func (Entry) Infof

func (e Entry) Infof(msg string, v ...interface{})

Infof level message.

func (Entry) Panic

func (e Entry) Panic(msg string)

Panic level message.

func (Entry) Panicf

func (e Entry) Panicf(msg string, v ...interface{})

Panicf level message.

func (Entry) Stop

func (e Entry) Stop()

Stop should be used with Trace, to fire off the completion message. When an `err` is passed the "error" field is set, and the log level is error.

func (Entry) Trace

func (e Entry) Trace(msg string) Entry

Trace returns a new entry with a Stop method to fire off a corresponding completion log, useful with defer.

func (Entry) Warn

func (e Entry) Warn(msg string)

Warn level message.

func (Entry) Warnf

func (e Entry) Warnf(msg string, v ...interface{})

Warnf level message.

func (Entry) WithError

func (e Entry) WithError(err error) Entry

WithError returns a new entry with the "error" set to `err`.

func (Entry) WithField

func (e Entry) WithField(key string, value interface{}) Entry

WithField returns a new entry with the `key` and `value` set.

func (Entry) WithFields

func (e Entry) WithFields(fields Fields) Entry

WithFields adds the provided fields to the current entry

type Fields

type Fields map[string]interface{}

Fields represents a map of entry level data used for structured logging.

func (Fields) Get

func (f Fields) Get(name string) interface{}

Get field value by name.

func (Fields) Names

func (f Fields) Names() (v []string)

Names returns field names sorted. map is not

type Flusher

type Flusher interface {
	Flush() error
}

Flusher is an interface that allow handles have the ability to clear buffer and close connection

type Handler

type Handler interface {
	Log(Entry) error
}

Handler is an interface that log handlers need to be implemented

type Level

type Level uint8

Level of the log

const (
	DebugLevel Level = iota
	InfoLevel
	WarnLevel
	ErrorLevel
	PanicLevel
	FatalLevel
)

Log levels.

func GetLevelsFromMinLevel

func GetLevelsFromMinLevel(minLevel string) []Level

GetLevelsFromMinLevel returns Levels array which above minLevel

func (Level) String

func (p Level) String() string

String returns the string representation of a logging level.

Directories

Path Synopsis
handlers
discard
Package discard implements a no-op handler useful for benchmarks and tests.
Package discard implements a no-op handler useful for benchmarks and tests.
memory
Package memory implements an in-memory handler useful for testing, as the entries can be accessed after writes.
Package memory implements an in-memory handler useful for testing, as the entries can be accessed after writes.

Jump to

Keyboard shortcuts

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