zlog

package module
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2019 License: MIT Imports: 16 Imported by: 0

README

zlog

What is a log tool I really want

I want to a log tool which provide help for reading through others codes, especially a big bounch of codes.

So the tool should like:

  • It helps to show how the code runs
  • Pretty showing key arguments
  • Help to analyze data flow

And it should like below:

>>>> something is wrong                                         (app)[2018-07-09 18:07:57]
     - a=1
     - b=2
     - because the weather is not good
**** something is not working well                              (app/module1)[2018-07-09 18:07:57]
     - some one tole me the sun go  into cloud

---- This is normal output                                      (app/module2)[2018-07-09 18:07:57]
     {
       "a":1,
       "b":"abc",
     }

API Example

The simplest way to use zlog is simply the package-level exported logger:

package main

import (
  log "github.com/ssor/zlog"
)

func main() {
  log.WithFields(log.Fields{
    "animal": "walrus",
  }).Info("A walrus appears")
}

Note that it's completely api-compatible with the stdlib logger, so you can replace your log imports everywhere with log "github.com/ssor/zlog" and you'll now have the flexibility of Zlog. You can customize it all you want:

package main

import (
  "os"
  log "github.com/ssor/zlog"
)

func init() {
  // Output to stderr instead of stdout, could also be a file.
  log.SetOutput(os.Stderr)

  // Only log the warning severity or above.
  log.SetLevel(log.WarnLevel)
}

func main() {
  log.WithFields(log.Fields{
    "animal": "walrus",
    "size":   10,
  }).Info("A group of walrus emerges from the ocean")

  log.WithFields(log.Fields{
    "omg":    true,
    "number": 122,
  }).Warn("The group's number increased tremendously!")

  log.WithFields(log.Fields{
    "omg":    true,
    "number": 100,
  }).Fatal("The ice breaks!")

  // A common pattern is to re-use fields between logging statements by re-using
  contextLogger := log.WithFields(log.Fields{
    "common": "this is a common field",
    "other": "I also should be logged always",
  })

  contextLogger.Info("I'll be logged with common and other field")
  contextLogger.Info("Me too")
}
Fields

Zlog encourages careful, structured logging though logging fields instead of long, unparseable error messages. For example, instead of: log.Fatalf("Failed to send event %s to topic %s with key %d"), you should log the much more discoverable:

log.WithFields(log.Fields{
  "event": event,
  "topic": topic,
  "key": key,
}).Fatal("Failed to send event")

We've found this API forces you to think about logging in a way that produces much more useful logging messages. We've been in countless situations where just a single added field to a log statement that was already there would've saved us hours. The WithFields call is optional.

Documentation

Overview

Package logrus is a structured logger for Go, completely API compatible with the standard library logger.

The simplest way to use Logrus is simply the package-level exported logger:

package main

import (
  log "github.com/lytics/logrus"
)

func main() {
  log.WithFields(log.Fields{
    "animal": "walrus",
    "number": 1,
    "size":   10,
  }).Info("A walrus appears")
}

Output:

time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10

For a full guide visit https://github.com/lytics/logrus

Index

Constants

View Source
const DefaultTimestampFormat = "2006-01-02 15:04:05"

Variables

A constant exposing all logging levels

View Source
var ErrorKey = "error"

Defines the key when adding errors using WithError.

Functions

func Debug

func Debug(args ...interface{})

Debug logs a message at level Debug on the standard logger.

func Debugf

func Debugf(format string, args ...interface{})

Debugf logs a message at level Debug on the standard logger.

func Debugln

func Debugln(args ...interface{})

Debugln logs a message at level Debug on the standard logger.

func DumpStacks

func DumpStacks()

func Error

func Error(args ...interface{})

Error logs a message at level Error on the standard logger.

func Errorf

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

Errorf logs a message at level Error on the standard logger.

func Errorln

func Errorln(args ...interface{})

Errorln logs a message at level Error on the standard logger.

func Failed added in v1.0.4

func Failed(args ...interface{})

func Failedf added in v1.0.4

func Failedf(format string, args ...interface{})

func Fatal

func Fatal(args ...interface{})

Fatal logs a message at level Fatal on the standard logger.

func Fatalf

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

Fatalf logs a message at level Fatal on the standard logger.

func Fatalln

func Fatalln(args ...interface{})

Fatalln logs a message at level Fatal on the standard logger.

func Highlight

func Highlight(args ...interface{})

func Highlightf

func Highlightf(format string, args ...interface{})

func Info

func Info(args ...interface{})

Info logs a message at level Info on the standard logger.

func Infof

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

Infof logs a message at level Info on the standard logger.

func Infoln

func Infoln(args ...interface{})

Infoln logs a message at level Info on the standard logger.

func IsTerminal

func IsTerminal() bool

IsTerminal returns true if stderr's file descriptor is a terminal.

func Panic

func Panic(args ...interface{})

Panic logs a message at level Panic on the standard logger.

func Panicf

func Panicf(format string, args ...interface{})

Panicf logs a message at level Panic on the standard logger.

func Panicln

func Panicln(args ...interface{})

Panicln logs a message at level Panic on the standard logger.

func Pass added in v1.0.4

func Pass(args ...interface{})

func Passf added in v1.0.4

func Passf(format string, args ...interface{})

func PrettyJson

func PrettyJson(j []byte)

func Print

func Print(args ...interface{})

Print logs a message at level Info on the standard logger.

func Printf

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

Printf logs a message at level Info on the standard logger.

func Println

func Println(args ...interface{})

Println logs a message at level Info on the standard logger.

func SetLevel

func SetLevel(level Level)

SetLevel sets the standard logger level.

func SetOutput

func SetOutput(out io.Writer)

SetOutput sets the standard logger output.

func SetPrintLineNumber

func SetPrintLineNumber(b bool)

func Success added in v1.0.4

func Success(args ...interface{})

func Successf added in v1.0.4

func Successf(format string, args ...interface{})

func Trace

func Trace(index int, fields Fields, obj interface{}, args ...interface{})

func TraceArgs

func TraceArgs(index int, args ...interface{})

func TraceArgsDefault

func TraceArgsDefault(args ...interface{})

func TraceDefault

func TraceDefault(fields Fields, obj interface{}, args ...interface{})

func TraceEnd

func TraceEnd(index int)

func TraceEndDefault

func TraceEndDefault()

func TraceFileds

func TraceFileds(index int, fields Fields)

func TraceFiledsDefault

func TraceFiledsDefault(fields Fields)

func TraceWithStruct

func TraceWithStruct(index int, obj interface{})

func TraceWithStructDefault

func TraceWithStructDefault(obj interface{})

func Warn

func Warn(args ...interface{})

Warn logs a message at level Warn on the standard logger.

func Warnf

func Warnf(format string, args ...interface{})

Warnf logs a message at level Warn on the standard logger.

func Warningf

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

Warningf logs a message at level Warn on the standard logger.

func Warningln

func Warningln(args ...interface{})

Warningln logs a message at level Warn on the standard logger.

func Warnln

func Warnln(args ...interface{})

Warnln logs a message at level Warn on the standard logger.

Types

type Entry

type Entry struct {
	Logger *Logger

	// Contains all the fields set by the user.
	Data Fields

	// Time at which the log entry was created
	Time time.Time

	// Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic
	Level Level

	// Message passed to Debug, Info, Warn, Error, Fatal or Panic
	Message string

	// When formatter is called in entry.log(), an Buffer may be set to entry
	Buffer *bytes.Buffer

	JsonRawList []byte
}

An entry is the final or intermediate Logrus logging entry. It contains all the fields passed with WithField{,s}. It's finally logged when Debug, Info, Warn, Error, Fatal or Panic is called on it. These objects can be reused and passed around as much as you wish to avoid field duplication.

func AddFields

func AddFields(args ...interface{}) *Entry

func NewEntry

func NewEntry(logger *Logger, moduleName string) *Entry

func WithError

func WithError(err error) *Entry

WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.

func WithField

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

WithField creates an entry from the standard logger and adds a field to it. If you want multiple fields, use `WithFields`.

Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal or Panic on the Entry it returns.

func WithFields

func WithFields(fields Fields) *Entry

WithFields creates an entry from the standard logger and adds multiple fields to it. This is simply a helper for `WithField`, invoking it once for each field.

Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal or Panic on the Entry it returns.

func WithJsonRaw

func WithJsonRaw(bs []byte) *Entry

func WithLongString

func WithLongString(key, longStr, sep string) *Entry

func WithMultiLines

func WithMultiLines(key, longStr string) *Entry

func WithStruct

func WithStruct(value interface{}) *Entry

func (*Entry) Debug

func (entry *Entry) Debug(args ...interface{})

func (*Entry) Debugf

func (entry *Entry) Debugf(format string, args ...interface{})

func (*Entry) Debugln

func (entry *Entry) Debugln(args ...interface{})

func (*Entry) Error

func (entry *Entry) Error(args ...interface{})

func (*Entry) Errorf

func (entry *Entry) Errorf(format string, args ...interface{})

func (*Entry) Errorln

func (entry *Entry) Errorln(args ...interface{})

func (*Entry) Fatal

func (entry *Entry) Fatal(args ...interface{})

func (*Entry) Fatalf

func (entry *Entry) Fatalf(format string, args ...interface{})

func (*Entry) Fatalln

func (entry *Entry) Fatalln(args ...interface{})

func (*Entry) GetBuffer

func (entry *Entry) GetBuffer() *bytes.Buffer

func (*Entry) GetData

func (entry *Entry) GetData() Fields

func (*Entry) GetJsonRaw

func (entry *Entry) GetJsonRaw() []byte

func (*Entry) GetLevel

func (entry *Entry) GetLevel() Level

func (*Entry) GetMessage

func (entry *Entry) GetMessage() string

func (*Entry) GetTime

func (entry *Entry) GetTime() time.Time

func (*Entry) Info

func (entry *Entry) Info(args ...interface{})

func (*Entry) Infof

func (entry *Entry) Infof(format string, args ...interface{})

func (*Entry) Infoln

func (entry *Entry) Infoln(args ...interface{})

func (*Entry) Panic

func (entry *Entry) Panic(args ...interface{})

func (*Entry) Panicf

func (entry *Entry) Panicf(format string, args ...interface{})

func (*Entry) Panicln

func (entry *Entry) Panicln(args ...interface{})

func (*Entry) Print

func (entry *Entry) Print(args ...interface{})

func (*Entry) Printf

func (entry *Entry) Printf(format string, args ...interface{})

func (*Entry) Println

func (entry *Entry) Println(args ...interface{})

func (*Entry) String

func (entry *Entry) String() (string, error)

Returns the string representation from the reader and ultimately the formatter.

func (*Entry) Warn

func (entry *Entry) Warn(args ...interface{})

func (*Entry) Warnf

func (entry *Entry) Warnf(format string, args ...interface{})

func (*Entry) Warning

func (entry *Entry) Warning(args ...interface{})

func (*Entry) Warningf

func (entry *Entry) Warningf(format string, args ...interface{})

func (*Entry) Warningln

func (entry *Entry) Warningln(args ...interface{})

func (*Entry) Warnln

func (entry *Entry) Warnln(args ...interface{})

func (*Entry) WithError

func (entry *Entry) WithError(err error) *Entry

Add an error as single field (using the key defined in ErrorKey) to the Entry.

func (*Entry) WithField

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

Add a single field to the Entry.

func (*Entry) WithFields

func (entry *Entry) WithFields(fields Fields) *Entry

Add a map of fields to the Entry.

func (*Entry) WithJsonRaw

func (entry *Entry) WithJsonRaw(bs []byte) *Entry

func (*Entry) WithLongString

func (entry *Entry) WithLongString(key, longStr, sep string) *Entry

func (*Entry) WithMultiLines

func (entry *Entry) WithMultiLines(key, longStr string) *Entry

type FieldLogger

type FieldLogger interface {
	WithField(key string, value interface{}) *Entry
	WithFields(fields Fields) *Entry
	WithError(err error) *Entry

	Debugf(format string, args ...interface{})
	Infof(format string, args ...interface{})
	Printf(format string, args ...interface{})
	Warnf(format string, args ...interface{})
	Warningf(format string, args ...interface{})
	Errorf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
	Panicf(format string, args ...interface{})

	Debug(args ...interface{})
	Info(args ...interface{})
	Print(args ...interface{})
	Warn(args ...interface{})
	Warning(args ...interface{})
	Error(args ...interface{})
	Fatal(args ...interface{})
	Panic(args ...interface{})

	Debugln(args ...interface{})
	Infoln(args ...interface{})
	Println(args ...interface{})
	Warnln(args ...interface{})
	Warningln(args ...interface{})
	Errorln(args ...interface{})
	Fatalln(args ...interface{})
	Panicln(args ...interface{})
}

The FieldLogger interface generalizes the Entry and Logger types

type Fields

type Fields map[string]interface{}

Fields type, used to pass to `WithFields`.

type Formatter

type Formatter interface {
	Format(input FormatterInput, callDepth int) ([]byte, error)
}

The Formatter interface is used to implement a custom Formatter. It takes an `Entry`. It exposes all the fields, including the default ones:

* `entry.Data["msg"]`. The message passed from Info, Warn, Error .. * `entry.Data["time"]`. The timestamp. * `entry.Data["level"]. The level the entry was logged at.

Any additional fields added with `WithField` or `WithFields` are also in `entry.Data`. Format is expected to return an array of bytes which are then logged to `logger.Out`.

type FormatterInput

type FormatterInput interface {
	GetBuffer() *bytes.Buffer
	GetData() Fields
	GetTime() time.Time
	GetMessage() string
	GetLevel() Level
	GetJsonRaw() []byte
}

type Level

type Level uint8

Level type

const (
	// PanicLevel level, highest level of severity. Logs and then calls panic with the
	// message passed to Debug, Info, ...
	PanicLevel Level = iota
	// FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the
	// logging level is set to Panic.
	FatalLevel
	// ErrorLevel level. Logs. Used for errors that should definitely be noted.
	// Commonly used for hooks to send errors to an error tracking service.
	ErrorLevel
	// WarnLevel level. Non-critical entries that deserve eyes.
	WarnLevel
	// InfoLevel level. General operational entries about what's going on inside the
	// application.
	InfoLevel
	// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
	DebugLevel
)

These are the different logging levels. You can set the logging level to log on your instance of logger, obtained with `zlog.New()`.

func GetLevel

func GetLevel() Level

GetLevel returns the standard logger level.

func ParseLevel

func ParseLevel(lvl string) (Level, error)

ParseLevel takes a string level and returns the Logrus log level constant.

func (Level) String

func (level Level) String() string

Convert the Level to a string. E.g. PanicLevel becomes "panic".

type LevelParser

type LevelParser interface {
	Parse(*string) (Level, error)
}

type Logger

type Logger struct {
	// The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
	// file, or leave it default which is `os.Stderr`. You can also set this to
	// something more adventorous, such as logging to Kafka.
	Out io.Writer
	// All log entries pass through the formatter before logged to Out. The
	// included formatters are `TextFormatter` and `JSONFormatter` for which
	// TextFormatter is the default. In development (when a TTY is attached) it
	// logs with colors, but to a file it wouldn't. You can easily implement your
	// own that implements the `Formatter` interface, see the `README` or included
	// formatters for examples.
	Formatter Formatter
	// The logging level the logger should log at. This is typically (and defaults
	// to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
	// logged. `logrus.Debug` is useful in
	Level Level
	// contains filtered or unexported fields
}

func New

func New(moduleNames ...string) *Logger

Creates a new logger. Configuration should be set by changing `Formatter`, `Out` and `Hooks` directly on the default logger instance. You can also just instantiate your own:

var log = &Logger{
  Out: os.Stderr,
  Formatter: new(JSONFormatter),
  Hooks: make(LevelHooks),
  Level: logrus.DebugLevel,
}

It's recommended to make this a global instance called `log`.

func StandardLogger

func StandardLogger() *Logger

func (*Logger) Debug

func (logger *Logger) Debug(args ...interface{})

func (*Logger) Debugf

func (logger *Logger) Debugf(format string, args ...interface{})

func (*Logger) Debugln

func (logger *Logger) Debugln(args ...interface{})

func (*Logger) Error

func (logger *Logger) Error(args ...interface{})

func (*Logger) Errorf

func (logger *Logger) Errorf(format string, args ...interface{})

func (*Logger) Errorln

func (logger *Logger) Errorln(args ...interface{})

func (*Logger) Failed added in v1.0.4

func (logger *Logger) Failed(args ...interface{})

func (*Logger) Failedf added in v1.0.4

func (logger *Logger) Failedf(format string, args ...interface{})

func (*Logger) Fatal

func (logger *Logger) Fatal(args ...interface{})

func (*Logger) Fatalf

func (logger *Logger) Fatalf(format string, args ...interface{})

func (*Logger) Fatalln

func (logger *Logger) Fatalln(args ...interface{})

func (*Logger) Highlight

func (logger *Logger) Highlight(args ...interface{})

func (*Logger) Highlightf

func (logger *Logger) Highlightf(format string, args ...interface{})

func (*Logger) Info

func (logger *Logger) Info(args ...interface{})

func (*Logger) Infof

func (logger *Logger) Infof(format string, args ...interface{})

func (*Logger) Infoln

func (logger *Logger) Infoln(args ...interface{})

func (*Logger) Name added in v1.0.6

func (logger *Logger) Name() string

func (*Logger) Panic

func (logger *Logger) Panic(args ...interface{})

func (*Logger) Panicf

func (logger *Logger) Panicf(format string, args ...interface{})

func (*Logger) Panicln

func (logger *Logger) Panicln(args ...interface{})

func (*Logger) Pass added in v1.0.4

func (logger *Logger) Pass(args ...interface{})

func (*Logger) Passf added in v1.0.4

func (logger *Logger) Passf(format string, args ...interface{})

func (*Logger) Print

func (logger *Logger) Print(args ...interface{})

func (*Logger) Printf

func (logger *Logger) Printf(format string, args ...interface{})

func (*Logger) Println

func (logger *Logger) Println(args ...interface{})

func (*Logger) SetLevel

func (logger *Logger) SetLevel(level Level)

func (*Logger) SetNoLock

func (logger *Logger) SetNoLock()

When file is opened with appending mode, it's safe to write concurrently to a file (within 4k message on Linux). In these cases user can choose to disable the lock.

func (*Logger) SetOutput added in v1.0.5

func (logger *Logger) SetOutput(out io.Writer)

SetOutput sets the standard logger output.

func (*Logger) Success added in v1.0.4

func (logger *Logger) Success(args ...interface{})

func (*Logger) Successf added in v1.0.4

func (logger *Logger) Successf(format string, args ...interface{})

func (*Logger) Warn

func (logger *Logger) Warn(args ...interface{})

func (*Logger) Warnf

func (logger *Logger) Warnf(format string, args ...interface{})

func (*Logger) Warningf

func (logger *Logger) Warningf(format string, args ...interface{})

func (*Logger) Warningln

func (logger *Logger) Warningln(args ...interface{})

func (*Logger) Warnln

func (logger *Logger) Warnln(args ...interface{})

func (*Logger) WithError

func (logger *Logger) WithError(err error) *Entry

Add an error as single field to the log entry. All it does is call `WithError` for the given `error`.

func (*Logger) WithField

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

Adds a field to the log entry, note that it doesn't log until you call Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry. If you want multiple fields, use `WithFields`.

func (*Logger) WithFields

func (logger *Logger) WithFields(fields Fields) *Entry

Adds a struct of fields to the log entry. All it does is call `WithField` for each `Field`.

func (*Logger) WithJsonRaw

func (logger *Logger) WithJsonRaw(bs []byte) *Entry

func (*Logger) WithLongString

func (logger *Logger) WithLongString(key, longStr, sep string) *Entry

func (*Logger) WithMultiLines

func (logger *Logger) WithMultiLines(key, longStr string) *Entry

func (*Logger) WithStruct

func (logger *Logger) WithStruct(value interface{}) *Entry

func (*Logger) Writer

func (logger *Logger) Writer() *io.PipeWriter

func (*Logger) WriterLevel

func (logger *Logger) WriterLevel(level Level) *io.PipeWriter

type MutexWrap

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

func (*MutexWrap) Disable

func (mw *MutexWrap) Disable()

func (*MutexWrap) Lock

func (mw *MutexWrap) Lock()

func (*MutexWrap) Unlock

func (mw *MutexWrap) Unlock()

type PrefixStrCmp

type PrefixStrCmp struct{}

func (*PrefixStrCmp) Parse

func (p *PrefixStrCmp) Parse(s *string) (Level, error)

type RegexpParser

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

func (*RegexpParser) Parse

func (pr *RegexpParser) Parse(s *string) (Level, error)

type SeverityFormatter

type SeverityFormatter struct {
	// TimestampFormat sets the format used for marshaling timestamps.
	TimestampFormat string
}

func (*SeverityFormatter) Format

func (f *SeverityFormatter) Format(entry *Entry) ([]byte, error)

type StdLogger

type StdLogger interface {
	Print(...interface{})
	Printf(string, ...interface{})
	Println(...interface{})

	Fatal(...interface{})
	Fatalf(string, ...interface{})
	Fatalln(...interface{})

	Panic(...interface{})
	Panicf(string, ...interface{})
	Panicln(...interface{})
}

StdLogger is what your zlog-enabled library should take, that way it'll accept a stdlib logger and a zlog logger. There's no standard interface, this is the closest we get, unfortunately.

type Termios

type Termios syscall.Termios

type TextFormatter

type TextFormatter struct {
	// Set to true to bypass checking for a TTY before outputting colors.
	ForceColors bool

	// Force disabling colors.
	DisableColors bool

	// Disable timestamp logging. useful when output is redirected to logging
	// system that already adds timestamps.
	DisableTimestamp bool

	// Enable logging the full timestamp when a TTY is attached instead of just
	// the time passed since beginning of execution.
	FullTimestamp bool

	// TimestampFormat to use for display when a full timestamp is printed
	TimestampFormat string

	// The fields are sorted by default for a consistent output. For applications
	// that log extremely frequently and don't use the JSON formatter this may not
	// be desired.
	DisableSorting bool
}

func (*TextFormatter) Format

func (f *TextFormatter) Format(entry FormatterInput, callDepth int) ([]byte, error)

type TraceBlock

type TraceBlock struct {
	Fields Fields
	Obj    interface{}
	// contains filtered or unexported fields
}

type TraceChain

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

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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