log

package module
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2020 License: MIT Imports: 16 Imported by: 180

README

Structured Logging for Humans

godoc goreport license

Features

  • No external dependences
  • Simple & Straightforward interfaces
  • JSON/TSV/GRPC/Printf Loggers
  • Rotating File Writer
  • Pretty Console Writer(with windows 7/8/10 support)
  • Dynamic log Level
  • High Performance

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("a structured logger")
}

// Output:
//   {"time":"2020-03-22T09:58:41.828Z","level":"debug","message":"Hello, 世界"}
//   {"time":"2020-03-22T09:58:41.828Z","level":"info","foo":"bar","number":42,"message":"a structure logger"}

Note: By default log writes to os.Stderr

Pretty logging

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

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

log.Printf("a printf style line")
log.Info().Err(errors.New("an error")).Int("everything", 42).Str("foo", "bar").Msg("hello world")

Pretty logging

Note: pretty logging also works on windows console

Dynamic log Level

To change log level on the fly, use log.DefaultLogger.SetLevel. playground

log.DefaultLogger.SetLevel(log.InfoLevel)
log.Debug().Msg("debug log")
log.Info().Msg("info log")
log.Warn().Msg("warn log")
log.DefaultLogger.SetLevel(log.DebugLevel)
log.Debug().Msg("debug log")
log.Info().Msg("info log")

// Output:
//   {"time":"2020-03-24T05:06:54.674Z","level":"info","message":"info log"}
//   {"time":"2020-03-24T05:06:54.674Z","level":"warn","message":"warn log"}
//   {"time":"2020-03-24T05:06:54.675Z","level":"debug","message":"debug log"}
//   {"time":"2020-03-24T05:06:54.675Z","level":"info","message":"info log"}
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().Msg("hello world")

// Output: {"date":"2019-07-04","level":"info","caller":"test.go:42","message":"hello world"}
Logging to syslog
package main

import (
	"log/syslog"

	"github.com/phuslu/log"
)

func main() {
	logger, err := syslog.NewLogger(syslog.LOG_INFO, 0)
	if err != nil {
		log.Fatal().Err(err).Msg("new syslog error")
	}

	log.DefaultLogger.Writer = logger.Writer()
	log.Info().Str("foo", "bar").Msg("a syslog message")
}
Rotating log files hourly
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",
			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")
	}
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultLogger = Logger{
	Level:      DebugLevel,
	Caller:     0,
	TimeField:  "",
	TimeFormat: "",
	Timestamp:  false,
	HostField:  "",
	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 IsTerminal

func IsTerminal(fd uintptr) bool

IsTerminal returns whether the given file descriptor is a terminal.

func Print

func Print(v ...interface{})

Print sends a log event using debug level and no extra field. Arguments are handled in the manner of fmt.Print.

func Printf

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

Printf sends a log event using debug level and no extra field. Arguments are handled in the manner of fmt.Printf.

Types

type ConsoleWriter

type ConsoleWriter struct {
	ANSIColor bool
}

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

func (*ConsoleWriter) Write

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

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 Warn

func Warn() (e *Event)

Warn starts a new message with warning level.

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) 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) Caller

func (e *Event) Caller() *Event

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

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) 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) 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) 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) 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) 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) 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) 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.

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 megabytes 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
	// backup 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 backup files.
	HostName bool
	// contains filtered or unexported fields
}

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

FileWriter opens or creates the logfile on first Write. If the file exists and is less than MaxSize megabytes, FileWriter will open and append to that file. If the file exists and its size is >= MaxSize megabytes, the file is renamed by putting the current time in a timestamp in the name immediately before the file's extension (or the end of the filename if there's no extension). A new log file is then created using original filename.

Whenever a write would cause the current log file exceed MaxSize megabytes, the current file is closed, renamed, and a new log file created with the original name. Thus, the filename you give FileWriter is always the "current" log file.

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.FileWriter. 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 {
	Logger Logger
}

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

func (GrpcLogger) Error

func (l GrpcLogger) Error(args ...interface{})

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

func (GrpcLogger) Errorf

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

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

func (GrpcLogger) Errorln

func (l GrpcLogger) Errorln(args ...interface{})

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

func (GrpcLogger) Fatal

func (l 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 (l 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 (l 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 (l GrpcLogger) Info(args ...interface{})

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

func (GrpcLogger) Infof

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

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

func (GrpcLogger) Infoln

func (l GrpcLogger) Infoln(args ...interface{})

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

func (GrpcLogger) V

func (l GrpcLogger) V(level int) bool

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

func (GrpcLogger) Warning

func (l GrpcLogger) Warning(args ...interface{})

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

func (GrpcLogger) Warningf

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

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

func (GrpcLogger) Warningln

func (l GrpcLogger) Warningln(args ...interface{})

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

type Level

type Level uint32

Level defines log levels.

const (
	// DebugLevel defines debug log level.
	DebugLevel Level = iota
	// InfoLevel defines info log level.
	InfoLevel
	// WarnLevel defines warn log level.
	WarnLevel
	// ErrorLevel defines error log level.
	ErrorLevel
	// FatalLevel defines fatal log level.
	FatalLevel
	// PanicLevel defines panic log level.
	PanicLevel
	// NoLevel defines an absent log level.
	NoLevel
	// Disabled disables the logger.
	Disabled
)

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.

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 format of the Time field type.
	TimeField string

	// TimeFormat specifies the format for timestamp in output.
	TimeFormat string

	// Timestamp determines if time is formatted as an UNIX timestamp as integer.
	// If set, the value of TimeField and TimeFormat will be ignored.
	Timestamp bool

	// HostField specifies the key for hostname in output if not empty
	HostField string

	// TimeField 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) Info

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

Info starts a new message with info level.

func (Logger) Print

func (l Logger) Print(v ...interface{})

Print sends a log event using debug level and no extra field. Arguments are handled in the manner of fmt.Print.

func (Logger) Printf

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

Printf sends a log event using debug level and no 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) 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 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 append the val as a bool 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) 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

type Writer = FileWriter

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