log

package module
v1.0.39 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2020 License: MIT Imports: 25 Imported by: 180

README

Structured Logging for Humans

go.dev goreport build coverage stability-stable

Features

  • No Dependencies
  • Intuitive Interfaces
  • Consistent Writers
    • FileWriter, rotating & robust
    • ConsoleWriter, colorful & templating
    • MultiWriter, multiple level dispatch
    • AsyncWriter, asynchronously writing
    • JournalWriter, systemd logging
    • EventlogWriter, windows system event
  • Third-party(StdLog/Grpc/Logr) Logger Interceptor
  • High Performance

Interfaces

Logger
// DefaultLogger is the global logger.
var DefaultLogger = Logger{
	Level:      DebugLevel,
	Caller:     0,
	TimeField:  "",
	TimeFormat: "",
	Writer:     os.Stderr,
}

// A Logger represents an active logging object that generates lines of JSON output to an io.Writer.
type Logger struct {
	// Level defines log levels.
	Level Level

	// Caller determines if adds the file:line of the "caller" key.
	Caller int

	// TimeField defines the time filed name in output.  It uses "time" in if empty.
	TimeField string

	// TimeFormat specifies the time format in output. It uses time.RFC3389 in if empty.
	// If set with `TimeFormatUnix`, `TimeFormatUnixMs`, times are formated as UNIX timestamp.
	TimeFormat string

	// Writer specifies the writer of output. It uses os.Stderr in if empty.
	Writer io.Writer
}
FileWriter & ConsoleWriter
// FileWriter is an io.WriteCloser that writes to the specified filename.
type FileWriter struct {
	// Filename is the file to write logs to.  Backup log files will be retained
	// in the same directory.
	Filename string

	// FileMode represents the file's mode and permission bits.  The default
	// mode is 0644
	FileMode os.FileMode

	// MaxSize is the maximum size in bytes of the log file before it gets rotated.
	MaxSize int64

	// MaxBackups is the maximum number of old log files to retain.  The default
	// is to retain all old log files
	MaxBackups int

	// LocalTime determines if the time used for formatting the timestamps in
	// log files is the computer's local time.  The default is to use UTC time.
	LocalTime bool

	// HostName determines if the hostname used for formatting in log files.
	HostName bool

	// ProcessID determines if the pid used for formatting in log files.
	ProcessID bool
}

// ConsoleWriter parses the JSON input and writes it in an
// (optionally) colorized, human-friendly format to output Writer.
//
// Default output format:
//     {Time} {Level} {Goid} {Caller} > {Message} {Key}={Value} {Key}={Value}
//
// Note: ConsoleWriter performance is not good, it will parses JSON input into
// structured records, then outputs them in a specific order.
type ConsoleWriter struct {
	// ColorOutput determines if used colorized output.
	ColorOutput bool

	// QuoteString determines if quoting string values.
	QuoteString bool

	// EndWithMessage determines if output message in the end.
	EndWithMessage bool

	// Template specifies an optional text/template for creating a
	// user-defined output format, available arguments are:
	//    type . struct {
	//        Time     string    // "2019-07-10T05:35:54.277Z"
	//        Level    Level     // log.InfoLevel
	//        Caller   string    // "prog.go:42"
	//        Goid     string    // "123"
	//        Message  string    // "a structure message"
	//        Stack    string    // "<stack string>"
	//        KeyValue []struct {
	//            Key   string       // "foo"
	//            Value string       // "bar"
	//        }
	//    }
	// See https://github.com/phuslu/log#template-console-writer for example.
	//
	// If Template is not nil, ColorOutput, QuoteString and EndWithMessage are override.
	Template *template.Template

	// Writer is the output destination. using os.Stderr if empty.
	Writer io.Writer
}

Getting Started

Simple Logging Example

A out of box example. playground

package main

import (
	"github.com/phuslu/log"
)

func main() {
	log.Printf("Hello, %s", "世界")
	log.Info().Str("foo", "bar").Int("number", 42).Msg("hi, phuslog")
	log.Error().Str("foo", "bar").Int("number", 42).Msgf("oops, %s", "phuslog")
}

// Output:
//   {"time":"2020-03-22T09:58:41.828Z","message":"Hello, 世界"}
//   {"time":"2020-03-22T09:58:41.828Z","level":"info","foo":"bar","number":42,"message":"hi, phuslog"}
//   {"time":"2020-03-22T09:58:41.828Z","level":"error","foo":"bar","number":42,"message":"oops, phuslog"}

Note: By default log writes to os.Stderr

Customize the configuration and formatting:

To customize logger filed name and format. playground

log.DefaultLogger = log.Logger{
	Level:      log.InfoLevel,
	Caller:     1,
	TimeField:  "date",
	TimeFormat: "2006-01-02",
	Writer:     os.Stderr,
}
log.Info().Str("foo", "bar").Msgf("hello %s", "world")

// Output: {"date":"2019-07-04","level":"info","caller":"prog.go:16","foo":"bar","message":"hello world"}
Rotating File Writer

To log to a rotating file, use FileWriter. playground

package main

import (
	"time"

	"github.com/phuslu/log"
	"github.com/robfig/cron/v3"
)

func main() {
	logger := log.Logger{
		Level:      log.ParseLevel("info"),
		Writer:     &log.FileWriter{
			Filename:   "main.log",
			FileMode:   0600,
			MaxSize:    50*1024*1024,
			MaxBackups: 7,
			LocalTime:  false,
		},
	}

	runner := cron.New(cron.WithSeconds(), cron.WithLocation(time.UTC))
	runner.AddFunc("0 0 * * * *", func() { logger.Writer.(*log.FileWriter).Rotate() })
	go runner.Run()

	for {
		time.Sleep(time.Second)
		logger.Info().Msg("hello world")
	}
}
Pretty Console Writer

To log a human-friendly, colorized output, use ConsoleWriter. playground

if log.IsTerminal(os.Stderr.Fd()) {
	log.DefaultLogger = log.Logger{
		Caller: 1,
		Writer: &log.ConsoleWriter{
			ColorOutput:    true,
			QuoteString:    true,
			EndWithMessage: true,
		},
	}
}

log.Debug().Int("everything", 42).Str("foo", "bar").Msg("hello world")
log.Info().Int("everything", 42).Str("foo", "bar").Msg("hello world")
log.Warn().Int("everything", 42).Str("foo", "bar").Msg("hello world")
log.Error().Err(errors.New("an error")).Msg("hello world")

Pretty logging

Note: pretty logging also works on windows console

Template Console Writer

To log with user-defined format(e.g. glog), using ConsoleWriter.Template. playground

package main

import (
	"text/template"
	"github.com/phuslu/log"
)

var glog = (&log.Logger{
	Level:      log.InfoLevel,
	Caller:     1,
	TimeFormat: "0102 15:04:05.999999",
	Writer: &log.ConsoleWriter{
		Template: template.Must(template.New("").Parse(
			`{{.Level.First}}{{.Time}} {{.Goid}} {{.Caller}}] {{.Message}}`)),
	},
}).Sugar(nil)

func main() {
	glog.Infof("hello glog %s", "Info")
	glog.Warnf("hello glog %s", "Earn")
	glog.Errorf("hello glog %s", "Error")
	glog.Fatalf("hello glog %s", "Fatal")
}

// Output:
// I0725 09:59:57.503246 19 console_test.go:183] hello glog Info
// W0725 09:59:57.504247 19 console_test.go:184] hello glog Earn
// E0725 09:59:57.504247 19 console_test.go:185] hello glog Error
// F0725 09:59:57.504247 19 console_test.go:186] hello glog Fatal

Note: refer to ColorTemplate and sprig to make it functional.

MultiWriter & AsyncWriter & JournalWriter & EventlogWriter

To log to different writers by different levels, use MultiWriter.

log.DefaultLogger.Writer = &log.MultiWriter{
	InfoWriter:   &log.FileWriter{Filename: "main.INFO"},
	WarnWriter:   &log.FileWriter{Filename: "main.WARNING"},
	ErrorWriter:  &log.FileWriter{Filename: "main.ERROR"},
	StderrWriter: &log.ConsoleWriter{ColorOutput: true},
	StderrLevel:  log.ErrorLevel,
}
log.Info().Int("number", 42).Str("foo", "bar").Msg("a info log")
log.Warn().Int("number", 42).Str("foo", "bar").Msg("a warn log")
log.Error().Int("number", 42).Str("foo", "bar").Msg("a error log")

To log to file asynchronously for maximize performance, use AsyncWriter.

file, _ := os.OpenFile("main.log", os.O_WRONLY, 0644)
log.DefaultLogger.Writer = &log.AsyncWriter{
	Writer: file,
}
log.Info().Int("number", 42).Str("foo", "bar").Msg("a async info log")
log.Warn().Int("number", 42).Str("foo", "bar").Msg("a async warn log")
log.DefaultLogger.Writer.(io.Closer).Close()

To log to linux systemd journald, using JournalWriter.

log.DefaultLogger.Writer = &log.JournalWriter{}
log.Info().Int("number", 42).Str("foo", "bar").Msg("hello world")

To log to windows system event, using EventlogWriter.

log.DefaultLogger.Writer = &log.EventlogWriter{
	Source: ".NET Runtime",
	ID:     1000,
}
log.Info().Int("number", 42).Str("foo", "bar").Msg("hello world")
Sugar Logger

In contexts where performance is nice, but not critical, use the SugaredLogger. It's 20% slower than Logger but still faster than other structured logging packages playground

package main

import (
	"github.com/phuslu/log"
)

func main() {
	sugar := log.DefaultLogger.Sugar(log.NewContext(nil).Str("tag", "hi suagr").Value())
	sugar.Infof("hello %s", "世界")
	sugar.Infow("i am a leading message", "foo", "bar", "number", 42)

	sugar = sugar.Level(log.ErrorLevel)
	sugar.Printf("hello %s", "世界")
	sugar.Log("number", 42, "a_key", "a_value", "message", "a suagr message")
}
StdLog & Logr & Grpc Interceptor

Using wrapped loggers for stdlog/grpc/logr. playground

package main

import (
	stdLog "log"
	"github.com/go-logr/logr"
	"github.com/phuslu/log"
	"google.golang.org/grpc/grpclog"
)

func main() {
	ctx := log.NewContext(nil).Str("tag", "hi log").Value()

	var stdlog *stdLog.Logger = log.DefaultLogger.Std(log.InfoLevel, ctx, "prefix ", stdLog.LstdFlags)
	stdlog.Print("hello from stdlog Print")
	stdlog.Println("hello from stdlog Println")
	stdlog.Printf("hello from stdlog %s", "Printf")

	var grpclog grpclog.LoggerV2 = log.DefaultLogger.Grpc(ctx)
	grpclog.Infof("hello %s", "grpclog Infof message")
	grpclog.Errorf("hello %s", "grpclog Errorf message")

	var logrLog logr.Logger = log.DefaultLogger.Logr(ctx)
	logrLog = logrLog.WithName("a_named_logger").WithValues("a_key", "a_value")
	logrLog.Info("hello", "foo", "bar", "number", 42)
	logrLog.Error(errors.New("this is a error"), "hello", "foo", "bar", "number", 42)
}
Contextual Fields

To add preserved key:value pairs to each event, use NewContext. playground

ctx := log.NewContext(nil).Str("ctx_str", "a ctx str").Value()

logger := log.Logger{Level: log.InfoLevel}
logger.Debug().Context(ctx).Int("no0", 0).Msg("zero")
logger.Info().Context(ctx).Int("no1", 1).Msg("first")
logger.Info().Context(ctx).Int("no2", 2).Msg("second")

// Output:
//   {"time":"2020-07-12T05:03:43.949Z","level":"info","ctx_str":"a ctx str","no1":1,"message":"first"}
//   {"time":"2020-07-12T05:03:43.949Z","level":"info","ctx_str":"a ctx str","no2":2,"message":"second"}
High Performance

A quick and simple benchmark with logrus/zap/zerolog, which runs on github actions:

// go test -v -run=none -bench=. -benchtime=10s -benchmem log_test.go
package main

import (
	"io/ioutil"
	"testing"

	"github.com/phuslu/log"
	"github.com/rs/zerolog"
	"github.com/sirupsen/logrus"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var fakeMessage = "Test logging, but use a somewhat realistic message length. "

func BenchmarkLogrus(b *testing.B) {
	logger := logrus.New()
	logger.SetFormatter(&logrus.JSONFormatter{})
	logger.SetOutput(ioutil.Discard)
	for i := 0; i < b.N; i++ {
		logger.WithFields(logrus.Fields{"foo": "bar", "int": 42}).Info(fakeMessage)
	}
}

func BenchmarkZap(b *testing.B) {
	logger := zap.New(zapcore.NewCore(
		zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
		zapcore.AddSync(ioutil.Discard),
		zapcore.InfoLevel,
	))
	for i := 0; i < b.N; i++ {
		logger.Info(fakeMessage, zap.String("foo", "bar"), zap.Int("int", 42))
	}
}

func BenchmarkZeroLog(b *testing.B) {
	logger := zerolog.New(ioutil.Discard).With().Timestamp().Logger()
	for i := 0; i < b.N; i++ {
		logger.Info().Str("foo", "bar").Int("int", 42).Msg(fakeMessage)
	}
}

func BenchmarkPhusLog(b *testing.B) {
	logger := log.Logger{Writer: ioutil.Discard}
	for i := 0; i < b.N; i++ {
		logger.Info().Str("foo", "bar").Int("int", 42).Msg(fakeMessage)
	}
}

Performance results on 2020-08-20 test

BenchmarkLogrus-2    	 2548255	      4737 ns/op	    1832 B/op	      31 allocs/op
BenchmarkZap-2       	11387668	      1074 ns/op	     128 B/op	       1 allocs/op
BenchmarkZeroLog-2   	21846039	       548 ns/op	       0 B/op	       0 allocs/op
BenchmarkPhusLog-2   	51170454	       233 ns/op	       0 B/op	       0 allocs/op
Acknowledgment

This log is heavily inspired by zerolog, glog, quicktemplate, zap and lumberjack.

Documentation

Index

Constants

View Source
const (
	// TimeFormatUnix defines a time format that makes time fields to be
	// serialized as Unix timestamp integers.
	TimeFormatUnix = "\x01"

	// TimeFormatUnixMs defines a time format that makes time fields to be
	// serialized as Unix timestamp integers in milliseconds.
	TimeFormatUnixMs = "\x02"
)
View Source
const ColorTemplate = `` /* 550-byte string literal not displayed */

ColorTemplate provides a pre-defined text/template for console color output Note: use [sprig](https://github.com/Masterminds/sprig) to introduce more template functions.

Variables

View Source
var ColorFuncMap = template.FuncMap{
	"black":      func(s string) string { return "\x1b[30m" + s + "\x1b[0m" },
	"red":        func(s string) string { return "\x1b[31m" + s + "\x1b[0m" },
	"green":      func(s string) string { return "\x1b[32m" + s + "\x1b[0m" },
	"yellow":     func(s string) string { return "\x1b[33m" + s + "\x1b[0m" },
	"blue":       func(s string) string { return "\x1b[34m" + s + "\x1b[0m" },
	"magenta":    func(s string) string { return "\x1b[35m" + s + "\x1b[0m" },
	"cyan":       func(s string) string { return "\x1b[36m" + s + "\x1b[0m" },
	"white":      func(s string) string { return "\x1b[37m" + s + "\x1b[0m" },
	"gray":       func(s string) string { return "\x1b[90m" + s + "\x1b[0m" },
	"contains":   strings.Contains,
	"endswith":   strings.HasSuffix,
	"lower":      strings.ToLower,
	"match":      path.Match,
	"quote":      strconv.Quote,
	"startswith": strings.HasPrefix,
	"title":      strings.ToTitle,
	"upper":      strings.ToUpper,
}

ColorFuncMap provides a pre-defined template functions for color string

View Source
var DefaultLogger = Logger{
	Level:      DebugLevel,
	Caller:     0,
	TimeField:  "",
	TimeFormat: "",
	Writer:     os.Stderr,
}

DefaultLogger is the global logger.

Functions

func Fastrandn

func Fastrandn(x uint32) uint32

Fastrandn returns a pseudorandom uint32 in [0,n).

func Goid added in v1.0.29

func Goid() int64

Goid returns the current goroutine id. It exactly matches goroutine id of the stack trace.

func IsTerminal

func IsTerminal(fd uintptr) bool

IsTerminal returns whether the given file descriptor is a terminal.

func Printf

func Printf(format string, v ...interface{})

Printf sends a log event without extra field. Arguments are handled in the manner of fmt.Printf.

Types

type AsyncWriter added in v1.0.37

type AsyncWriter struct {
	// BufferSize is the size in bytes of the buffer, the default size is 32KB.
	BufferSize int

	// ChannelSize is the size of the data channel, the default size is 100.
	ChannelSize int

	// SyncDuration is the duration of the writer syncs, the default duration is 5s.
	SyncDuration time.Duration

	// Writer specifies the writer of output.
	Writer io.Writer
	// contains filtered or unexported fields
}

AsyncWriter is an io.WriteCloser that writes asynchronously.

func (*AsyncWriter) Close added in v1.0.37

func (w *AsyncWriter) Close() (err error)

Close implements io.Closer, and closes the underlying Writer.

func (*AsyncWriter) Sync added in v1.0.37

func (w *AsyncWriter) Sync() (err error)

Sync syncs all pending log I/O.

func (*AsyncWriter) Write added in v1.0.37

func (w *AsyncWriter) Write(p []byte) (n int, err error)

Write implements io.Writer. If a write would cause the log buffer to be larger than Size, the buffer is written to the underlying Writer and cleared.

type ConsoleWriter

type ConsoleWriter struct {
	// ColorOutput determines if used colorized output.
	ColorOutput bool

	// QuoteString determines if quoting string values.
	QuoteString bool

	// EndWithMessage determines if output message in the end.
	EndWithMessage bool

	// Template specifies an optional text/template for creating a
	// user-defined output format, available arguments are:
	//    type . struct {
	//        Time     string    // "2019-07-10T05:35:54.277Z"
	//        Level    Level     // InfoLevel
	//        Caller   string    // "prog.go:42"
	//        Goid     string    // "123"
	//        Message  string    // "a structure message"
	//        Stack    string    // "<stack string>"
	//        KeyValue []struct {
	//            Key   string       // "foo"
	//            Value string       // "bar"
	//        }
	//    }
	// See https://github.com/phuslu/log#template-console-writer for example.
	//
	// If Template is not nil, ColorOutput, QuoteString and EndWithMessage are override.
	Template *template.Template

	// Writer is the output destination. using os.Stderr if empty.
	Writer io.Writer
}

ConsoleWriter parses the JSON input and writes it in an (optionally) colorized, human-friendly format to Writer.

Default output format:

{Time} {Level} {Goid} {Caller} > {Message} {Key}={Value} {Key}={Value}

Note: ConsoleWriter performance is not good, it will parses JSON input into structured records, then outputs them in a specific order.

func (*ConsoleWriter) Close added in v1.0.39

func (w *ConsoleWriter) Close() (err error)

Close implements io.Closer, will closes the underlying Writer if not empty.

func (*ConsoleWriter) Write

func (w *ConsoleWriter) Write(p []byte) (int, error)

type Context added in v1.0.20

type Context []byte

Context represents contextual fields.

type Event

type Event struct {
	// contains filtered or unexported fields
}

Event represents a log event. It is instanced by one of the level method of Logger and finalized by the Msg or Msgf method.

func Debug

func Debug() (e *Event)

Debug starts a new message with debug level.

func Error

func Error() (e *Event)

Error starts a new message with error level.

func Fatal

func Fatal() (e *Event)

Fatal starts a new message with fatal level.

func Info

func Info() (e *Event)

Info starts a new message with info level.

func NewContext added in v1.0.20

func NewContext(dst []byte) (e *Event)

NewContext starts a new contextual event.

func Panic added in v1.0.29

func Panic() (e *Event)

Panic starts a new message with panic level.

func Trace added in v1.0.33

func Trace() (e *Event)

Trace starts a new message with trace level.

func Warn

func Warn() (e *Event)

Warn starts a new message with warning level.

func (*Event) AnErr added in v1.0.18

func (e *Event) AnErr(key string, err error) *Event

AnErr adds the field key with serialized err to the logger context.

func (*Event) Bool

func (e *Event) Bool(key string, b bool) *Event

Bool append append the val as a bool to the event.

func (*Event) Bools

func (e *Event) Bools(key string, b []bool) *Event

Bools adds the field key with val as a []bool to the event.

func (*Event) Byte added in v1.0.33

func (e *Event) Byte(key string, val byte) *Event

Byte adds the field key with val as a byte to the event.

func (*Event) Bytes

func (e *Event) Bytes(key string, val []byte) *Event

Bytes adds the field key with val as a string to the event.

func (*Event) BytesOrNil added in v1.0.24

func (e *Event) BytesOrNil(key string, val []byte) *Event

BytesOrNil adds the field key with val as a string or nil to the event.

func (*Event) Caller

func (e *Event) Caller(depth int) *Event

Caller adds the file:line of the "caller" key.

func (*Event) Context added in v1.0.20

func (e *Event) Context(ctx Context) *Event

Context sends the contextual fields to event.

func (*Event) Dict added in v1.0.20

func (e *Event) Dict(key string, ctx Context) *Event

Dict sends the contextual fields with key to event.

func (*Event) Discard

func (e *Event) Discard() *Event

Discard disables the event so Msg(f) won't print it.

func (*Event) Dur

func (e *Event) Dur(key string, d time.Duration) *Event

Dur adds the field key with duration d to the event.

func (*Event) Durs

func (e *Event) Durs(key string, d []time.Duration) *Event

Durs adds the field key with val as a []time.Duration to the event.

func (*Event) Enabled

func (e *Event) Enabled() bool

Enabled return false if the event is going to be filtered out by log level.

func (*Event) Err

func (e *Event) Err(err error) *Event

Err adds the field "error" with serialized err to the event.

func (*Event) Errs

func (e *Event) Errs(key string, errs []error) *Event

Errs adds the field key with errs as an array of serialized errors to the event.

func (*Event) Fields added in v1.0.35

func (e *Event) Fields(fields map[string]interface{}) *Event

Fields is a helper function to use a map to set fields using type assertion.

func (*Event) Float32

func (e *Event) Float32(key string, f float32) *Event

Float32 adds the field key with f as a float32 to the event.

func (*Event) Float64

func (e *Event) Float64(key string, f float64) *Event

Float64 adds the field key with f as a float64 to the event.

func (*Event) Floats32

func (e *Event) Floats32(key string, f []float32) *Event

Floats32 adds the field key with f as a []float32 to the event.

func (*Event) Floats64

func (e *Event) Floats64(key string, f []float64) *Event

Floats64 adds the field key with f as a []float64 to the event.

func (*Event) GoStringer added in v1.0.17

func (e *Event) GoStringer(key string, val fmt.GoStringer) *Event

GoStringer adds the field key with val.GoStringer() to the event.

func (*Event) Hex

func (e *Event) Hex(key string, val []byte) *Event

Hex adds the field key with val as a hex string to the event.

func (*Event) IPAddr added in v1.0.10

func (e *Event) IPAddr(key string, ip net.IP) *Event

IPAddr adds IPv4 or IPv6 Address to the event

func (*Event) IPPrefix added in v1.0.10

func (e *Event) IPPrefix(key string, pfx net.IPNet) *Event

IPPrefix adds IPv4 or IPv6 Prefix (address and mask) to the event

func (*Event) Int

func (e *Event) Int(key string, i int) *Event

Int adds the field key with i as a int to the event.

func (*Event) Int16

func (e *Event) Int16(key string, i int16) *Event

Int16 adds the field key with i as a int16 to the event.

func (*Event) Int32

func (e *Event) Int32(key string, i int32) *Event

Int32 adds the field key with i as a int32 to the event.

func (*Event) Int64

func (e *Event) Int64(key string, i int64) *Event

Int64 adds the field key with i as a int64 to the event.

func (*Event) Int8

func (e *Event) Int8(key string, i int8) *Event

Int8 adds the field key with i as a int8 to the event.

func (*Event) Interface

func (e *Event) Interface(key string, i interface{}) *Event

Interface adds the field key with i marshaled using reflection.

func (*Event) MACAddr added in v1.0.10

func (e *Event) MACAddr(key string, ha net.HardwareAddr) *Event

MACAddr adds MAC address to the event

func (*Event) Msg

func (e *Event) Msg(msg string)

Msg sends the event with msg added as the message field if not empty.

func (*Event) Msgf

func (e *Event) Msgf(format string, v ...interface{})

Msgf sends the event with formatted msg added as the message field if not empty.

func (*Event) RawJSON

func (e *Event) RawJSON(key string, b []byte) *Event

RawJSON adds already encoded JSON to the log line under key.

func (*Event) RawJSONStr added in v1.0.28

func (e *Event) RawJSONStr(key string, s string) *Event

RawJSONStr adds already encoded JSON String to the log line under key.

func (*Event) Stack added in v1.0.10

func (e *Event) Stack() *Event

Stack enables stack trace printing for the error passed to Err().

func (*Event) Str

func (e *Event) Str(key string, val string) *Event

Str adds the field key with val as a string to the event.

func (*Event) Stringer added in v1.0.15

func (e *Event) Stringer(key string, val fmt.Stringer) *Event

Stringer adds the field key with val.String() to the event.

func (*Event) Strs

func (e *Event) Strs(key string, vals []string) *Event

Strs adds the field key with vals as a []string to the event.

func (*Event) Time

func (e *Event) Time(key string, t time.Time) *Event

Time append append t formated as string using time.RFC3339Nano.

func (*Event) TimeDiff added in v1.0.10

func (e *Event) TimeDiff(key string, t time.Time, start time.Time) *Event

TimeDiff adds the field key with positive duration between time t and start. If time t is not greater than start, duration will be 0. Duration format follows the same principle as Dur().

func (*Event) TimeFormat added in v1.0.2

func (e *Event) TimeFormat(key string, timefmt string, t time.Time) *Event

TimeFormat append append t formated as string using timefmt.

func (*Event) Uint16

func (e *Event) Uint16(key string, i uint16) *Event

Uint16 adds the field key with i as a uint16 to the event.

func (*Event) Uint32

func (e *Event) Uint32(key string, i uint32) *Event

Uint32 adds the field key with i as a uint32 to the event.

func (*Event) Uint64

func (e *Event) Uint64(key string, i uint64) *Event

Uint64 adds the field key with i as a uint64 to the event.

func (*Event) Uint8

func (e *Event) Uint8(key string, i uint8) *Event

Uint8 adds the field key with i as a uint8 to the event.

func (*Event) Value added in v1.0.20

func (e *Event) Value() Context

Value builds the contextual fields.

func (*Event) Xid added in v1.0.27

func (e *Event) Xid(key string, xid [12]byte) *Event

Xid adds the field key with xid.ID as a base32 string to the event.

type FileWriter added in v1.0.8

type FileWriter struct {
	// Filename is the file to write logs to.  Backup log files will be retained
	// in the same directory.
	Filename string

	// MaxSize is the maximum size in bytes of the log file before it gets rotated.
	MaxSize int64

	// MaxBackups is the maximum number of old log files to retain.  The default
	// is to retain all old log files
	MaxBackups int

	// FileMode represents the file's mode and permission bits.  The default
	// mode is 0644
	FileMode os.FileMode

	// LocalTime determines if the time used for formatting the timestamps in
	// log files is the computer's local time.  The default is to use UTC time.
	LocalTime bool

	// HostName determines if the hostname used for formatting in log files.
	HostName bool

	// ProcessID determines if the pid used for formatting in log files.
	ProcessID bool
	// contains filtered or unexported fields
}

FileWriter is an io.WriteCloser that writes to the specified filename.

Backups use the log file name given to FileWriter, in the form `name.timestamp.ext` where name is the filename without the extension, timestamp is the time at which the log was rotated formatted with the time.Time format of `2006-01-02T15-04-05` and the extension is the original extension. For example, if your FileWriter.Filename is `/var/log/foo/server.log`, a backup created at 6:30pm on Nov 11 2016 would use the filename `/var/log/foo/server.2016-11-04T18-30-00.log`

Cleaning Up Old Log Files

Whenever a new logfile gets created, old log files may be deleted. The most recent files according to the encoded timestamp will be retained, up to a number equal to MaxBackups (or all of them if MaxBackups is 0). Any files with an encoded timestamp older than MaxAge days are deleted, regardless of MaxBackups. Note that the time encoded in the timestamp is the rotation time, which may differ from the last time that file was written to.

func (*FileWriter) Close added in v1.0.8

func (w *FileWriter) Close() (err error)

Close implements io.Closer, and closes the current logfile.

func (*FileWriter) Rotate added in v1.0.8

func (w *FileWriter) Rotate() (err error)

Rotate causes Logger to close the existing log file and immediately create a new one. This is a helper function for applications that want to initiate rotations outside of the normal rotation rules, such as in response to SIGHUP. After rotating, this initiates compression and removal of old log files according to the configuration.

func (*FileWriter) Write added in v1.0.8

func (w *FileWriter) Write(p []byte) (n int, err error)

Write implements io.Writer. If a write would cause the log file to be larger than MaxSize, the file is closed, renamed to include a timestamp of the current time, and a new log file is created using the original log file name. If the length of the write is greater than MaxSize, an error is returned.

type GrpcLogger

type GrpcLogger struct {
	// contains filtered or unexported fields
}

GrpcLogger implements methods to satisfy interface google.golang.org/grpc/grpclog.LoggerV2.

func (*GrpcLogger) Error

func (g *GrpcLogger) Error(args ...interface{})

Error logs to ERROR log. Arguments are handled in the manner of fmt.Print.

func (*GrpcLogger) Errorf

func (g *GrpcLogger) Errorf(format string, args ...interface{})

Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.

func (*GrpcLogger) Errorln

func (g *GrpcLogger) Errorln(args ...interface{})

Errorln logs to ERROR log. Arguments are handled in the manner of fmt.Println.

func (*GrpcLogger) Fatal

func (g *GrpcLogger) Fatal(args ...interface{})

Fatal logs to ERROR log. Arguments are handled in the manner of fmt.Print. gRPC ensures that all Fatal logs will exit with os.Exit(1). Implementations may also call os.Exit() with a non-zero exit code.

func (*GrpcLogger) Fatalf

func (g *GrpcLogger) Fatalf(format string, args ...interface{})

Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. gRPC ensures that all Fatal logs will exit with os.Exit(1). Implementations may also call os.Exit() with a non-zero exit code.

func (*GrpcLogger) Fatalln

func (g *GrpcLogger) Fatalln(args ...interface{})

Fatalln logs to ERROR log. Arguments are handled in the manner of fmt.Println. gRPC ensures that all Fatal logs will exit with os.Exit(1). Implementations may also call os.Exit() with a non-zero exit code.

func (*GrpcLogger) Info

func (g *GrpcLogger) Info(args ...interface{})

Info logs to INFO log. Arguments are handled in the manner of fmt.Print.

func (*GrpcLogger) Infof

func (g *GrpcLogger) Infof(format string, args ...interface{})

Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf.

func (*GrpcLogger) Infoln

func (g *GrpcLogger) Infoln(args ...interface{})

Infoln logs to INFO log. Arguments are handled in the manner of fmt.Println.

func (*GrpcLogger) V

func (g *GrpcLogger) V(level int) bool

V reports whether verbosity level l is at least the requested verbose leveg.

func (*GrpcLogger) Warning

func (g *GrpcLogger) Warning(args ...interface{})

Warning logs to WARNING log. Arguments are handled in the manner of fmt.Print.

func (*GrpcLogger) Warningf

func (g *GrpcLogger) Warningf(format string, args ...interface{})

Warningf logs to WARNING log. Arguments are handled in the manner of fmt.Printf.

func (*GrpcLogger) Warningln

func (g *GrpcLogger) Warningln(args ...interface{})

Warningln logs to WARNING log. Arguments are handled in the manner of fmt.Println.

type JournalWriter added in v1.0.34

type JournalWriter struct {
	// JournalSocket specifies socket name, using `/run/systemd/journal/socket` if empty.
	JournalSocket string
	// contains filtered or unexported fields
}

JournalWriter is an io.WriteCloser that writes logs to journald.

func (*JournalWriter) Close added in v1.0.34

func (w *JournalWriter) Close() (err error)

Close implements io.Closer.

func (*JournalWriter) Write added in v1.0.34

func (w *JournalWriter) Write(p []byte) (n int, err error)

Write implements io.Writer.

type Level

type Level int32

Level defines log levels.

const (
	// TraceLevel defines trace log level.
	TraceLevel Level = -1
	// DebugLevel defines debug log level.
	DebugLevel Level = 0
	// InfoLevel defines info log level.
	InfoLevel Level = 1
	// WarnLevel defines warn log level.
	WarnLevel Level = 2
	// ErrorLevel defines error log level.
	ErrorLevel Level = 3
	// FatalLevel defines fatal log level.
	FatalLevel Level = 4
	// PanicLevel defines panic log level.
	PanicLevel Level = 5
)

func ParseLevel

func ParseLevel(s string) (level Level)

ParseLevel converts a level string into a log Level value. returns an error if the input string does not match known values.

func (Level) First added in v1.0.33

func (l Level) First() (s string)

First return first upper letter of Level

func (Level) Lower added in v1.0.29

func (l Level) Lower() (s string)

Lower return lowe case string of Level

func (Level) Three added in v1.0.29

func (l Level) Three() (s string)

Three return three letters of Level

func (Level) Title added in v1.0.29

func (l Level) Title() (s string)

Title return title case string of Level

func (Level) Upper added in v1.0.29

func (l Level) Upper() (s string)

Upper return upper case string of Level

type Logger

type Logger struct {
	// Level defines log levels.
	Level Level

	// Caller determines if adds the file:line of the "caller" key.
	Caller int

	// TimeField defines the time filed name in output.  It uses "time" in if empty.
	TimeField string

	// TimeFormat specifies the time format in output. It uses time.RFC3389 in if empty.
	// If set with `TimeFormatUnix`, `TimeFormatUnixMs`, times are formated as UNIX timestamp.
	TimeFormat string

	// Writer specifies the writer of output. It uses os.Stderr in if empty.
	Writer io.Writer
}

A Logger represents an active logging object that generates lines of JSON output to an io.Writer.

func (*Logger) Debug

func (l *Logger) Debug() (e *Event)

Debug starts a new message with debug level.

func (*Logger) Error

func (l *Logger) Error() (e *Event)

Error starts a new message with error level.

func (*Logger) Fatal

func (l *Logger) Fatal() (e *Event)

Fatal starts a new message with fatal level.

func (*Logger) Grpc added in v1.0.24

func (l *Logger) Grpc(context Context) (g *GrpcLogger)

Grpc wraps the Logger to provide a LoggerV2 logger

func (*Logger) Info

func (l *Logger) Info() (e *Event)

Info starts a new message with info level.

func (*Logger) Log added in v1.0.35

func (l *Logger) Log() (e *Event)

Log starts a new message with no level.

func (*Logger) Logr added in v1.0.31

func (l *Logger) Logr(context Context) *LogrLogger

Logr wraps the Logger to provide a logr logger

func (*Logger) Panic added in v1.0.29

func (l *Logger) Panic() (e *Event)

Panic starts a new message with panic level.

func (*Logger) Printf

func (l *Logger) Printf(format string, v ...interface{})

Printf sends a log event without extra field. Arguments are handled in the manner of fmt.Printf.

func (*Logger) SetLevel added in v1.0.4

func (l *Logger) SetLevel(level Level)

SetLevel changes logger default level.

func (*Logger) Std added in v1.0.26

func (l *Logger) Std(level Level, context Context, prefix string, flag int) *stdLog.Logger

Std wraps the Logger to provide *stdLog.Logger

func (*Logger) Sugar added in v1.0.23

func (l *Logger) Sugar(context Context) (s *SugaredLogger)

Sugar wraps the Logger to provide a more ergonomic, but a little bit slower, API. Sugaring a Logger is quite inexpensive, so it's reasonable for a single application to use both Loggers and SugaredLoggers, converting between them on the boundaries of performance-sensitive code.

func (*Logger) Trace added in v1.0.33

func (l *Logger) Trace() (e *Event)

Trace starts a new message with trace level.

func (*Logger) Warn

func (l *Logger) Warn() (e *Event)

Warn starts a new message with warning level.

func (*Logger) WithLevel

func (l *Logger) WithLevel(level Level) (e *Event)

WithLevel starts a new message with level.

type LogrLogger added in v1.0.31

type LogrLogger struct {
	// contains filtered or unexported fields
}

LogrLogger implements methods to satisfy interface github.com/go-logr/logr.Logger.

func (*LogrLogger) Enabled added in v1.0.31

func (l *LogrLogger) Enabled() bool

Enabled tests whether this Logger is enabled. For example, commandline flags might be used to set the logging verbosity and disable some info logs.

func (*LogrLogger) Error added in v1.0.31

func (l *LogrLogger) Error(err error, msg string, keysAndValues ...interface{})

Error logs an error, with the given message and key/value pairs as context. It functions similarly to calling Info with the "error" named value, but may have unique behavior, and should be preferred for logging errors (see the package documentations for more information).

The msg field should be used to add context to any underlying error, while the err field should be used to attach the actual error that triggered this log line, if present.

func (*LogrLogger) Info added in v1.0.31

func (l *LogrLogger) Info(msg string, keysAndValues ...interface{})

Info logs a non-error message with the given key/value pairs as context.

The msg argument should be used to add some constant description to the log line. The key/value pairs can then be used to add additional variable information. The key/value pairs should alternate string keys and arbitrary values.

func (*LogrLogger) V added in v1.0.31

func (l *LogrLogger) V(level int) *LogrLogger

V returns an Logger value for a specific verbosity level, relative to this Logger. In other words, V values are additive. V higher verbosity level means a log message is less important. It's illegal to pass a log level less than zero.

func (*LogrLogger) WithName added in v1.0.31

func (l *LogrLogger) WithName(name string) *LogrLogger

WithName adds a new element to the logger's name. Successive calls with WithName continue to append suffixes to the logger's name. It's strongly recommended that name segments contain only letters, digits, and hyphens (see the package documentation for more information).

func (*LogrLogger) WithValues added in v1.0.31

func (l *LogrLogger) WithValues(keysAndValues ...interface{}) *LogrLogger

WithValues adds some key-value pairs of context to a logger. See Info for documentation on how key/value pairs work.

type MultiWriter added in v1.0.34

type MultiWriter struct {
	// InfoWriter specifies all the level logs writes to
	InfoWriter io.Writer

	// WarnWriter specifies the level large than warn logs writes to
	WarnWriter io.Writer

	// WarnWriter specifies the level large than error logs writes to
	ErrorWriter io.Writer

	// StderrWriter specifies the stderr writer
	StderrWriter io.Writer

	// StderrLevel specifies the minimal level logs it will be writes to stderr
	StderrLevel Level

	// ParseLevel specifies an optional callback for parse log level from JSON input
	ParseLevel func([]byte) Level
}

MultiWriter is an io.WriteCloser that log to different writers by different levels

func (*MultiWriter) Close added in v1.0.34

func (w *MultiWriter) Close() (err error)

Close implements io.Closer, and closes the underlying LeveledWriter.

func (*MultiWriter) Write added in v1.0.34

func (w *MultiWriter) Write(p []byte) (n int, err error)

Write implements io.Writer.

type SugaredLogger added in v1.0.23

type SugaredLogger struct {
	// contains filtered or unexported fields
}

A SugaredLogger wraps the base Logger functionality in a slower, but less verbose, API. Any Logger can be converted to a SugaredLogger with its Sugar method.

Unlike the Logger, the SugaredLogger doesn't insist on structured logging. For each log level, it exposes three methods: one for loosely-typed structured logging, one for println-style formatting, and one for printf-style formatting.

func (*SugaredLogger) Debug added in v1.0.25

func (s *SugaredLogger) Debug(args ...interface{})

Debug uses fmt.Sprint to construct and log a message.

func (*SugaredLogger) Debugf added in v1.0.25

func (s *SugaredLogger) Debugf(template string, args ...interface{})

Debugf uses fmt.Sprintf to log a templated message.

func (*SugaredLogger) Debugw added in v1.0.25

func (s *SugaredLogger) Debugw(msg string, keysAndValues ...interface{})

Debugw logs a message with some additional context.

func (*SugaredLogger) Error added in v1.0.25

func (s *SugaredLogger) Error(args ...interface{})

Error uses fmt.Sprint to construct and log a message.

func (*SugaredLogger) Errorf added in v1.0.25

func (s *SugaredLogger) Errorf(template string, args ...interface{})

Errorf uses fmt.Sprintf to log a templated message.

func (*SugaredLogger) Errorw added in v1.0.25

func (s *SugaredLogger) Errorw(msg string, keysAndValues ...interface{})

Errorw logs a message with some additional context.

func (*SugaredLogger) Fatal added in v1.0.25

func (s *SugaredLogger) Fatal(args ...interface{})

Fatal uses fmt.Sprint to construct and log a message.

func (*SugaredLogger) Fatalf added in v1.0.25

func (s *SugaredLogger) Fatalf(template string, args ...interface{})

Fatalf uses fmt.Sprintf to log a templated message.

func (*SugaredLogger) Fatalw added in v1.0.25

func (s *SugaredLogger) Fatalw(msg string, keysAndValues ...interface{})

Fatalw logs a message with some additional context.

func (*SugaredLogger) Info added in v1.0.25

func (s *SugaredLogger) Info(args ...interface{})

Info uses fmt.Sprint to construct and log a message.

func (*SugaredLogger) Infof added in v1.0.25

func (s *SugaredLogger) Infof(template string, args ...interface{})

Infof uses fmt.Sprintf to log a templated message.

func (*SugaredLogger) Infow added in v1.0.25

func (s *SugaredLogger) Infow(msg string, keysAndValues ...interface{})

Infow logs a message with some additional context.

func (*SugaredLogger) Level added in v1.0.25

func (s *SugaredLogger) Level(level Level) *SugaredLogger

Level creates a child logger with the minimum accepted level set to level.

func (*SugaredLogger) Log added in v1.0.23

func (s *SugaredLogger) Log(keysAndValues ...interface{}) error

Log sends a log event with extra fields.

func (*SugaredLogger) Panic added in v1.0.29

func (s *SugaredLogger) Panic(args ...interface{})

Panic uses fmt.Sprint to construct and log a message.

func (*SugaredLogger) Panicf added in v1.0.29

func (s *SugaredLogger) Panicf(template string, args ...interface{})

Panicf uses fmt.Sprintf to log a templated message.

func (*SugaredLogger) Panicw added in v1.0.29

func (s *SugaredLogger) Panicw(msg string, keysAndValues ...interface{})

Panicw logs a message with some additional context.

func (*SugaredLogger) Print added in v1.0.23

func (s *SugaredLogger) Print(args ...interface{})

Print sends a log event without extra field. Arguments are handled in the manner of fmt.Print.

func (*SugaredLogger) Printf added in v1.0.23

func (s *SugaredLogger) Printf(format string, args ...interface{})

Printf sends a log event without extra field. Arguments are handled in the manner of fmt.Printf.

func (*SugaredLogger) Println added in v1.0.23

func (s *SugaredLogger) Println(args ...interface{})

Println sends a log event without extra field. Arguments are handled in the manner of fmt.Print.

func (*SugaredLogger) Warn added in v1.0.25

func (s *SugaredLogger) Warn(args ...interface{})

Warn uses fmt.Sprint to construct and log a message.

func (*SugaredLogger) Warnf added in v1.0.25

func (s *SugaredLogger) Warnf(template string, args ...interface{})

Warnf uses fmt.Sprintf to log a templated message.

func (*SugaredLogger) Warnw added in v1.0.25

func (s *SugaredLogger) Warnw(msg string, keysAndValues ...interface{})

Warnw logs a message with some additional context.

type TSVEvent

type TSVEvent struct {
	// contains filtered or unexported fields
}

TSVEvent represents a tsv log event. It is instanced by one of TSVLogger and finalized by the Msg method.

func (*TSVEvent) Bool

func (e *TSVEvent) Bool(b bool) *TSVEvent

Bool append the b as a bool to the event.

func (*TSVEvent) Byte added in v1.0.33

func (e *TSVEvent) Byte(b byte) *TSVEvent

Byte append the b as a byte to the event.

func (*TSVEvent) Bytes

func (e *TSVEvent) Bytes(val []byte) *TSVEvent

Bytes adds a bytes as string to the event.

func (*TSVEvent) Float32

func (e *TSVEvent) Float32(f float32) *TSVEvent

Float32 adds a float32 to the event.

func (*TSVEvent) Float64

func (e *TSVEvent) Float64(f float64) *TSVEvent

Float64 adds a float64 to the event.

func (*TSVEvent) IPAddr added in v1.0.10

func (e *TSVEvent) IPAddr(ip net.IP) *TSVEvent

IPAddr adds IPv4 or IPv6 Address to the event

func (*TSVEvent) Int

func (e *TSVEvent) Int(i int) *TSVEvent

Int adds a int to the event.

func (*TSVEvent) Int16

func (e *TSVEvent) Int16(i int16) *TSVEvent

Int16 adds a int16 to the event.

func (*TSVEvent) Int32

func (e *TSVEvent) Int32(i int32) *TSVEvent

Int32 adds a int32 to the event.

func (*TSVEvent) Int64

func (e *TSVEvent) Int64(i int64) *TSVEvent

Int64 adds a int64 to the event.

func (*TSVEvent) Int8

func (e *TSVEvent) Int8(i int8) *TSVEvent

Int8 adds a int8 to the event.

func (*TSVEvent) Msg

func (e *TSVEvent) Msg()

Msg sends the event.

func (*TSVEvent) Str

func (e *TSVEvent) Str(val string) *TSVEvent

Str adds a string to the event.

func (*TSVEvent) Timestamp

func (e *TSVEvent) Timestamp() *TSVEvent

Timestamp adds the current time as UNIX timestamp

func (*TSVEvent) TimestampMS added in v1.0.8

func (e *TSVEvent) TimestampMS() *TSVEvent

TimestampMS adds the current time with milliseconds as UNIX timestamp

func (*TSVEvent) Uint16

func (e *TSVEvent) Uint16(i uint16) *TSVEvent

Uint16 adds a uint16 to the event.

func (*TSVEvent) Uint32

func (e *TSVEvent) Uint32(i uint32) *TSVEvent

Uint32 adds a uint32 to the event.

func (*TSVEvent) Uint64

func (e *TSVEvent) Uint64(i uint64) *TSVEvent

Uint64 adds a uint64 to the event.

func (*TSVEvent) Uint8

func (e *TSVEvent) Uint8(i uint8) *TSVEvent

Uint8 adds a uint8 to the event.

type TSVLogger

type TSVLogger struct {
	Separator byte
	Writer    io.Writer
}

TSVLogger represents an active logging object that generates lines of TSV output to an io.Writer.

func (*TSVLogger) New

func (l *TSVLogger) New() (e *TSVEvent)

New starts a new tsv message.

type Writer deprecated

type Writer = FileWriter

Writer is an alias for FileWriter

Deprecated: Use FileWriter instead.

Directories

Path Synopsis
fiber module
logr module

Jump to

Keyboard shortcuts

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