slog

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2020 License: MIT Imports: 16 Imported by: 186

README

slog

GitHub go.mod Go version GoDoc Go Report Card Unit-Tests GitHub tag (latest SemVer)

A simple log library for Go.

Inspired the projects Seldaek/monolog and sirupsen/logrus. Thank you very much

中文说明

中文说明请阅读 README.zh-CN

Features

  • Simple, directly available without configuration
  • Multiple Handler log handlers can be added at the same time to output logs to different places
  • You can arbitrarily extend the Handler Formatter you need
  • Support to custom Handler
  • Support to custom Formatter

GoDoc

Install

go get github.com/gookit/slog

Usage

slog is very simple to use and can be used without any configuration

Quick Start

package main

import (
	"github.com/gookit/slog"
)

func main() {
	slog.Info("info log message")
	slog.Warn("warning log message")
	slog.Infof("info log %s", "message")
	slog.Debugf("debug %s", "message")
}

Output:

[2020/07/16 12:19:33] [application] [INFO] [main.go:7] info log message  
[2020/07/16 12:19:33] [application] [WARNING] [main.go:8] warning log message  
[2020/07/16 12:19:33] [application] [INFO] [main.go:9] info log message  
[2020/07/16 12:19:33] [application] [DEBUG] [main.go:10] debug message  
Console Color

You can enable color on output logs to console. This is default

package main

import (
	"github.com/gookit/slog"
)

func main() {
	slog.Configure(func(logger *slog.SugaredLogger) {
		f := logger.Formatter.(*slog.TextFormatter)
		f.EnableColor = true
	})

	slog.Trace("this is a simple log message")
	slog.Debug("this is a simple log message")
	slog.Info("this is a simple log message")
	slog.Notice("this is a simple log message")
	slog.Warn("this is a simple log message")
	slog.Error("this is a simple log message")
	slog.Fatal("this is a simple log message")
}

Output:

  • Change output format

Change the default logger output format.

slog.GetFormatter().(*slog.TextFormatter).Template = slog.NamedTemplate

Output:

Use JSON Format
package main

import (
	"github.com/gookit/slog"
)

func main() {
	// use JSON formatter
	slog.SetFormatter(slog.NewJSONFormatter())

	slog.Info("info log message")
	slog.Warn("warning log message")
	slog.WithData(slog.M{
		"key0": 134,
		"key1": "abc",
	}).Infof("info log %s", "message")

	r := slog.WithFields(slog.M{
		"category": "service",
		"IP": "127.0.0.1",
	})
	r.Infof("info %s", "message")
	r.Debugf("debug %s", "message")
}

Output:

{"channel":"application","data":{},"datetime":"2020/07/16 13:23:33","extra":{},"level":"INFO","message":"info log message"}
{"channel":"application","data":{},"datetime":"2020/07/16 13:23:33","extra":{},"level":"WARNING","message":"warning log message"}
{"channel":"application","data":{"key0":134,"key1":"abc"},"datetime":"2020/07/16 13:23:33","extra":{},"level":"INFO","message":"info log message"}
{"IP":"127.0.0.1","category":"service","channel":"application","datetime":"2020/07/16 13:23:33","extra":{},"level":"INFO","message":"info message"}
{"IP":"127.0.0.1","category":"service","channel":"application","datetime":"2020/07/16 13:23:33","extra":{},"level":"DEBUG","message":"debug message"}

Introduction

slog handle workflow(like monolog):

         Processors
Logger -{
         Handlers -{ With Formatters
Processor

Processor - Logging Record processor.

You can use it to perform additional operations on the record before the log record reaches the Handler for processing, such as adding fields, adding extended information, etc.

Processor definition:

// Processor interface definition
type Processor interface {
	// Process record
	Process(record *Record)
}

Processor func wrapper definition:

// ProcessorFunc wrapper definition
type ProcessorFunc func(record *Record)

// Process record
func (fn ProcessorFunc) Process(record *Record) {
	fn(record)
}

Here we use the built-in processor slog.AddHostname as an example, it can add a new field hostname to each log record.

slog.AddProcessor(slog.AddHostname())

slog.Info("message")

Output:

{"channel":"application","level":"INFO","datetime":"2020/07/17 12:01:35","hostname":"InhereMac","data":{},"extra":{},"message":"message"}
Handler

Handler - Log processor, each log will be processed by Handler.Handle(), where you can send the log to the console, file, or remote server.

You can customize any Handler you want, you only need to implement the slog.Handler interface.

// Handler interface definition
type Handler interface {
	// Close handler
	io.Closer
	// Flush logs to disk
	Flush() error
	// IsHandling Checks whether the given record will be handled by this handler.
	IsHandling(level Level) bool
	// Handle a log record.
	// all records may be passed to this method, and the handler should discard
	// those that it does not want to handle.
	Handle(*Record) error
}

Note: Remember to add the Handler to the logger instance before the log records will be processed by the Handler.

Formatter

Formatter - Log data formatting.

It is usually set in Handler, which can be used to format log records, convert records into text, JSON, etc., Handler then writes the formatted data to the specified place.

Formatter definition:

// Formatter interface
type Formatter interface {
	Format(record *Record) ([]byte, error)
}

Formatter function wrapper:

// FormatterFunc wrapper definition
type FormatterFunc func(r *Record) ([]byte, error)

// Format an record
func (fn FormatterFunc) Format(r *Record) ([]byte, error) {
	return fn(r)
}

Custom Logger

Create New Logger

You can create a new instance of slog.Logger:

  • Method 1:
l := slog.New()
// add handlers ...
h1 := handler.NewConsoleHandler(slog.AllLevels)
l.AddHandlers(h1)
  • Method 2:
l := slog.NewWithName("myLogger")
// add handlers ...
h1 := handler.NewConsoleHandler(slog.AllLevels)
l.AddHandlers(h1)
  • Method 3:
package main

import (
	"github.com/gookit/slog"
	"github.com/gookit/slog/handler"
)

func main() {
	l := slog.NewWithHandlers(handler.NewConsoleHandler(slog.AllLevels))
	l.Info("message")
}
Create New Handler

you only need implement the slog.Handler interface:

package mypkg

import (
	"github.com/gookit/slog"
	"github.com/gookit/slog/handler"
)

type MyHandler struct {
	handler.LevelsWithFormatter
}

func (h *MyHandler) Handle(r *slog.Record) error {
	// you can write log message to file or send to remote.
}

add handler to default logger:

slog.AddHander(&MyHandler{})

or add to custom logger:

l := slog.New()
l.AddHander(&MyHandler{})
Create New Processor

you only need implement the slog.Processor interface:

package mypkg

import (
	"github.com/gookit/slog"
	"github.com/gookit/slog/handler"
)

// AddHostname to record
func AddHostname() slog.Processor {
	hostname, _ := os.Hostname()

	return slog.ProcessorFunc(func(record *slog.Record) {
		record.AddField("hostname", hostname)
	})
}

add the processor:

slog.AddProcessor(mypkg.AddHostname())

or:

l := slog.New()
l.AddProcessor(mypkg.AddHostname())
Create New Formatter

you only need implement the slog.Formatter interface:

package mypkg

import (
	"github.com/gookit/slog"
)

type MyFormatter struct {
}

func (f *Formatter) Format(r *slog.Record) error {
	// format Record to text/JSON or other format.
}

add the formatter:

slog.SetFormatter(&mypkg.MyFormatter{})

OR:

l := slog.New()
h := &MyHandler{}
h.SetFormatter(&mypkg.MyFormatter{})

l.AddHander(h)

Refer

LICENSE

MIT

Documentation

Overview

Package slog A simple log library for Go.

Source code and other details for the project are available at GitHub:

https://github.com/gookit/slog

Quick usage:

package main

import (
	"github.com/gookit/slog"
)

func main() {
	slog.Info("info log message")
	slog.Warn("warning log message")
	slog.Infof("info log %s", "message")
	slog.Debugf("debug %s", "message")
}

More usage please see README.

Index

Examples

Constants

View Source
const (
	FieldKeyTime = "time"
	// FieldKeyDate  = "date"
	FieldKeyData = "data"
	// NOTICE: you must set `Logger.ReportCaller=true` for "func", "file"
	FieldKeyFunc = "func"
	FieldKeyFile = "file"

	FieldKeyDatetime  = "datetime"
	FieldKeyPosition  = "position"
	FieldKeyTimestamp = "timestamp"

	FieldKeyLevel = "level"
	FieldKeyError = "error"
	FieldKeyExtra = "extra"

	// NOTICE: you must set `Logger.ReportCaller=true` for "caller"
	FieldKeyCaller  = "caller"
	FieldKeyChannel = "channel"
	FieldKeyMessage = "message"
)
View Source
const DefaultTemplate = "[{{datetime}}] [{{channel}}] [{{level}}] [{{caller}}] {{message}} {{data}} {{extra}}\n"
View Source
const NamedTemplate = "{{datetime}} channel={{channel}} level={{level}} [file={{caller}}] message={{message}} data={{data}}\n"

Variables

View Source
var (
	DefaultChannelName = "application"
	DefaultTimeFormat  = "2006/01/02 15:04:05"
	// TimeFormatRFC3339  = time.RFC3339
	FieldKeys = struct {
		Level string
	}{
		Level: "level",
	}
)
View Source
var (
	// AllLevels exposing all logging levels
	AllLevels = []Level{
		PanicLevel,
		FatalLevel,
		ErrorLevel,
		WarnLevel,
		NoticeLevel,
		InfoLevel,
		DebugLevel,
		TraceLevel,
	}

	// PrintLevel for use logger.Print / Printf / Println
	PrintLevel = NoticeLevel

	// LevelNames all level mapping name
	LevelNames = map[Level]string{
		PanicLevel:  "PANIC",
		FatalLevel:  "FATAL",
		ErrorLevel:  "ERROR",
		NoticeLevel: "NOTICE",
		WarnLevel:   "WARNING",
		InfoLevel:   "INFO",
		DebugLevel:  "DEBUG",
		TraceLevel:  "TRACE",
	}
)
View Source
var (
	// DefaultFields default log export fields
	DefaultFields = []string{
		FieldKeyDatetime,
		FieldKeyChannel,
		FieldKeyLevel,
		FieldKeyCaller,
		FieldKeyMessage,
		FieldKeyData,
		FieldKeyExtra,
	}
	// NoTimeFields log export fields without time
	NoTimeFields = []string{
		FieldKeyChannel,
		FieldKeyLevel,
		FieldKeyMessage,
		FieldKeyData,
		FieldKeyExtra,
	}
)
View Source
var ColorTheme = map[Level]color.Color{
	FatalLevel:  color.FgRed,
	ErrorLevel:  color.FgMagenta,
	WarnLevel:   color.FgYellow,
	NoticeLevel: color.OpBold,
	InfoLevel:   color.FgGreen,
	DebugLevel:  color.FgCyan,
}

ColorTheme for format log to console

View Source
var (
	// Define the key when adding errors using WithError.
	ErrorKey = "error"
)

Functions

func AddHandler

func AddHandler(h Handler)

AddHandler to the std logger

func AddHandlers

func AddHandlers(hs ...Handler)

AddHandlers to the std logger

func AddProcessor

func AddProcessor(p Processor)

AddProcessor to the logger

func AddProcessors

func AddProcessors(ps ...Processor)

AddProcessors to the logger

func Configure

func Configure(fn func(logger *SugaredLogger))

Reset the std logger

func Debug

func Debug(args ...interface{})

Debug logs a message at level Debug

func Debugf

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

Debug logs a message at level Debug

func Error

func Error(args ...interface{})

Error logs a message at level Error

func Errorf

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

Error logs a message at level Error

func Exit

func Exit(code int)

Exit runs all the logger exit handlers and then terminates the program using os.Exit(code)

func ExitHandlers

func ExitHandlers() []func()

ExitHandlers get all global exitHandlers

func Fatal

func Fatal(args ...interface{})

Fatal logs a message at level Fatal

func Fatalf

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

Fatal logs a message at level Fatal

func Info

func Info(args ...interface{})

Info logs a message at level Info

func Infof

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

Info logs a message at level Info

func LevelName

func LevelName(l Level) string

LevelName match

func Notice

func Notice(args ...interface{})

Notice logs a message at level Notice

func Noticef

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

Notice logs a message at level Notice

func PrependExitHandler

func PrependExitHandler(handler func())

PrependExitHandler prepend register an exit-handler on global exitHandlers

func Print added in v0.0.3

func Print(args ...interface{})

Print logs a message at level PrintLevel

func Printf added in v0.0.3

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

Printf logs a message at level PrintLevel

func Println added in v0.0.3

func Println(args ...interface{})

Println logs a message at level PrintLevel

func RegisterExitHandler

func RegisterExitHandler(handler func())

PrependExitHandler register an exit-handler on global exitHandlers

func Reset

func Reset()

Reset the std logger

func ResetExitHandlers

func ResetExitHandlers(applyToStd bool)

ResetExitHandlers reset all exitHandlers

func SetExitFunc

func SetExitFunc(fn func(code int))

SetExitFunc to the std logger

func SetFormatter

func SetFormatter(f Formatter)

SetFormatter to std logger

func Trace

func Trace(args ...interface{})

Trace logs a message at level Trace

func Tracef

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

Trace logs a message at level Trace

func Warn

func Warn(args ...interface{})

Warn logs a message at level Warn

func Warnf

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

Warn logs a message at level Warn

Types

type FlushSyncWriter

type FlushSyncWriter interface {
	Flush() error
	Sync() error
	io.Writer
}

FlushSyncWriter is the interface satisfied by logging destinations.

type Formattable

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

Formattable definition

func (*Formattable) Formatter

func (f *Formattable) Formatter() Formatter

Formatter get formatter. if not set, will return TextFormatter

func (*Formattable) SetFormatter

func (f *Formattable) SetFormatter(formatter Formatter)

SetFormatter to handler

type FormattableHandler

type FormattableHandler interface {
	// Formatter get the log formatter
	Formatter() Formatter
	// SetFormatter set the log formatter
	SetFormatter(Formatter)
}

FormattableHandler interface

type Formatter

type Formatter interface {
	Format(record *Record) ([]byte, error)
}

Formatter interface

func GetFormatter

func GetFormatter() Formatter

GetFormatter of the std logger

type FormatterFunc

type FormatterFunc func(r *Record) ([]byte, error)

FormatterFunc wrapper definition

func (FormatterFunc) Format

func (fn FormatterFunc) Format(r *Record) ([]byte, error)

Format an record

type Handler

type Handler interface {
	// Close handler
	io.Closer
	// Flush logs to disk
	Flush() error
	// IsHandling Checks whether the given record will be handled by this handler.
	IsHandling(level Level) bool
	// Handle a log record.
	// all records may be passed to this method, and the handler should discard
	// those that it does not want to handle.
	Handle(*Record) error
}

Handler interface definition

type JSONFormatter

type JSONFormatter struct {
	// Fields exported log fields.
	Fields []string
	// Aliases for output fields. you can change export field name.
	// item: `"field" : "output name"`
	// eg: {"message": "msg"} export field will display "msg"
	Aliases StringMap

	// PrettyPrint will indent all json logs
	PrettyPrint bool
	// TimeFormat the time format layout. default is time.RFC3339
	TimeFormat string
}

JSONFormatter definition

func NewJSONFormatter

func NewJSONFormatter(fn ...func(*JSONFormatter)) *JSONFormatter

NewJSONFormatter create new JSONFormatter

func (*JSONFormatter) Configure

func (f *JSONFormatter) Configure(fn func(*JSONFormatter)) *JSONFormatter

Configure current formatter

func (*JSONFormatter) Format

func (f *JSONFormatter) Format(r *Record) ([]byte, error)

Format an log record

type Level

type Level uint32

Level type

const (
	// PanicLevel level, highest level of severity. will call panic() if the logging level <= PanicLevel.
	PanicLevel Level = 100
	// FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the
	// logging level <= FatalLevel.
	FatalLevel Level = 200
	// ErrorLevel level. Runtime errors. Used for errors that should definitely be noted.
	// Commonly used for hooks to send errors to an error tracking service.
	ErrorLevel Level = 300
	// WarnLevel level. Non-critical entries that deserve eyes.
	WarnLevel Level = 400
	// NoticeLevel level Uncommon events
	NoticeLevel Level = 500
	// InfoLevel level. Examples: User logs in, SQL logs.
	InfoLevel Level = 600
	// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
	DebugLevel Level = 700
	// TraceLevel level. Designates finer-grained informational events than the Debug.
	TraceLevel Level = 800
)

These are the different logging levels. You can set the logging level to log handler

func Name2Level

func Name2Level(ln string) (Level, error)

Name2Level convert name to level

func (Level) LowerName

func (l Level) LowerName() string

LowerName get lower level name

func (Level) Name

func (l Level) Name() string

Name get level name

func (Level) String

func (l Level) String() string

String get level name

type Logger

type Logger struct {
	ReportCaller   bool
	LowerLevelName bool
	MaxCallerDepth int

	ExitFunc func(code int)
	// contains filtered or unexported fields
}

Logger definition

func New

func New() *Logger

New create an new logger

Example
package main

import (
	"github.com/gookit/slog"
)

func main() {
	slog.Info("info log message")
	slog.Warn("warning log message")
	slog.Infof("info log %s", "message")
}
Output:

func NewWithConfig

func NewWithConfig(fn func(logger *Logger)) *Logger

NewWithConfig create an new logger with config func

func NewWithHandlers

func NewWithHandlers(hs ...Handler) *Logger

NewWithHandlers create an new logger with handlers

func NewWithName

func NewWithName(name string) *Logger

NewWithName create an new logger with name

func (*Logger) AddHandler

func (logger *Logger) AddHandler(h Handler)

AddHandler to the logger

func (*Logger) AddHandlers

func (logger *Logger) AddHandlers(hs ...Handler)

AddHandlers to the logger

func (*Logger) AddProcessor

func (logger *Logger) AddProcessor(p Processor)

AddProcessor to the logger

func (*Logger) AddProcessors

func (logger *Logger) AddProcessors(ps ...Processor)

AddProcessors to the logger

func (*Logger) Close

func (logger *Logger) Close()

Close the logger

func (*Logger) Configure

func (logger *Logger) Configure(fn func(logger *Logger)) *Logger

Configure current logger

func (*Logger) Debug

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

Debug logs a message at level Debug

func (*Logger) Debugf

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

Debug logs a message at level Debug

func (*Logger) Error

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

Error logs a message at level Error

func (*Logger) Errorf

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

Error logs a message at level Error

func (*Logger) Exit

func (logger *Logger) Exit(code int)

Exit logger handle

func (*Logger) ExitHandlers

func (logger *Logger) ExitHandlers() []func()

ExitHandlers get all exitHandlers of the logger

func (*Logger) Fatal

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

Fatal logs a message at level Fatal

func (*Logger) Fatalf

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

Fatal logs a message at level Fatal

func (*Logger) FlushAll

func (logger *Logger) FlushAll()

FlushAll flushes all the logs and attempts to "sync" their data to disk. logger.mu is held.

func (*Logger) FlushDaemon

func (logger *Logger) FlushDaemon()

FlushDaemon run flush handle on daemon

Usage:

go slog.FlushDaemon()

func (*Logger) Info

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

Info logs a message at level Info

func (*Logger) Infof

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

Info logs a message at level Info

func (*Logger) Log

func (logger *Logger) Log(level Level, args ...interface{})

Log an message

func (*Logger) Logf

func (logger *Logger) Logf(level Level, format string, args ...interface{})

Log an message

func (*Logger) Name

func (logger *Logger) Name() string

Name of the logger

func (*Logger) Notice

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

Notice logs a message at level Notice

func (*Logger) Noticef

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

Notice logs a message at level Notice

func (*Logger) Panic

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

Panic logs a message at level Panic

func (*Logger) Panicf

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

Panic logs a message at level Panic

func (*Logger) PrependExitHandler

func (logger *Logger) PrependExitHandler(handler func())

PrependExitHandler prepend register an exit-handler on global exitHandlers

func (*Logger) Print added in v0.0.3

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

Print logs a message at level PrintLevel

func (*Logger) Printf added in v0.0.3

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

Printf logs a message at level PrintLevel

func (*Logger) Println added in v0.0.3

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

Println logs a message at level PrintLevel

func (*Logger) PushHandler

func (logger *Logger) PushHandler(h Handler)

PushHandler to the logger. alias of AddHandler()

func (*Logger) PushProcessor

func (logger *Logger) PushProcessor(p Processor)

PushProcessor to the logger. alias of AddProcessor()

func (*Logger) RegisterExitHandler

func (logger *Logger) RegisterExitHandler(handler func())

PrependExitHandler register an exit-handler on global exitHandlers

func (*Logger) Reset

func (logger *Logger) Reset()

Reset the logger

func (*Logger) ResetExitHandlers

func (logger *Logger) ResetExitHandlers()

ResetExitHandlers reset logger exitHandlers

func (*Logger) ResetHandlers

func (logger *Logger) ResetHandlers()

ResetHandlers for the logger

func (*Logger) ResetProcessors

func (logger *Logger) ResetProcessors()

ResetProcessors for the logger

func (*Logger) SetHandlers

func (logger *Logger) SetHandlers(hs []Handler)

SetHandlers for the logger

func (*Logger) SetName

func (logger *Logger) SetName(name string) *Logger

SetName for logger

func (*Logger) SetProcessors

func (logger *Logger) SetProcessors(ps []Processor)

SetProcessors for the logger

func (*Logger) Sync

func (logger *Logger) Sync() error

Sync flushes buffered logs (if any).

func (*Logger) Trace

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

Trace logs a message at level Trace

func (*Logger) Tracef

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

Trace logs a message at level Trace

func (*Logger) VisitAll

func (logger *Logger) VisitAll(fn func(handler Handler) error)

VisitAll logger handlers

func (*Logger) Warn

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

Warn logs a message at level Warn

func (*Logger) Warnf

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

Warnf logs a message at level Warn

func (*Logger) Warning

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

Warning logs a message at level Warn

func (*Logger) WithContext

func (logger *Logger) WithContext(ctx context.Context) *Record

WithContext new record with context.Context

func (*Logger) WithData

func (logger *Logger) WithData(data M) *Record

WithData new record with data

func (*Logger) WithFields

func (logger *Logger) WithFields(fields M) *Record

SetFields new record with fields

func (*Logger) WithTime

func (logger *Logger) WithTime(t time.Time) *Record

WithTime new record with time.Time

type M

type M map[string]interface{}

M short name of map[string]interface{}

type Processable

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

Processable definition

func (*Processable) AddProcessor

func (p *Processable) AddProcessor(processor Processor)

AddProcessor to the handler

func (*Processable) ProcessRecord

func (p *Processable) ProcessRecord(r *Record)

ProcessRecord process records

type ProcessableHandler

type ProcessableHandler interface {
	// AddProcessor add an processor
	AddProcessor(Processor)
	// SetProcessor set the log processor
	ProcessRecord(record *Record)
}

ProcessableHandler interface

type Processor

type Processor interface {
	// Process record
	Process(record *Record)
}

Processor interface definition

func AddHostname

func AddHostname() Processor

AddHostname to record

func AddUniqueID added in v0.0.3

func AddUniqueID(fieldName string) Processor

AddUniqueID to record

type ProcessorFunc

type ProcessorFunc func(record *Record)

ProcessorFunc wrapper definition

var MemoryUsage ProcessorFunc = func(record *Record) {
	stat := new(runtime.MemStats)
	runtime.ReadMemStats(stat)
	record.Extra["memoryUsage"] = stat.Alloc
}

MemoryUsage Get memory usage.

func (ProcessorFunc) Process

func (fn ProcessorFunc) Process(record *Record)

Process record

type Record

type Record struct {
	Time  time.Time
	Level Level
	// level name from Level
	LevelName string

	// Channel log channel name. eg: "order", "goods", "user"
	Channel string
	Message string

	// Ctx context.Context
	Ctx context.Context

	// Buffer Can use Buffer on formatter
	Buffer *bytes.Buffer

	// Fields custom fields. Contains all the fields set by the user.
	Fields M

	// log data
	Data M

	// Extra log extra data
	Extra M

	// Caller information
	Caller *runtime.Frame
	// contains filtered or unexported fields
}

Record a log record definition

func WithData

func WithData(data M) *Record

WithData new record with data

func WithFields

func WithFields(fields M) *Record

WithFields new record with fields

func (*Record) AddData

func (r *Record) AddData(data M) *Record

AddData on record

func (*Record) AddExtra

func (r *Record) AddExtra(data M) *Record

AddExtra information on record

func (*Record) AddField

func (r *Record) AddField(name string, val interface{}) *Record

AddField add new field to the record

func (*Record) AddFields

func (r *Record) AddFields(fields M) *Record

AddFields add new fields to the record

func (*Record) AddValue

func (r *Record) AddValue(key string, value interface{}) *Record

AddValue add Data value to record

func (*Record) Copy

func (r *Record) Copy() *Record

Copy new record from old record

func (*Record) Debug

func (r *Record) Debug(args ...interface{})

Debug logs a message at level Debug

func (*Record) Debugf

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

Debug logs a message at level Debug

func (*Record) Error

func (r *Record) Error(args ...interface{})

Error logs a message at level Error

func (*Record) Errorf

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

Error logs a message at level Error

func (*Record) Fatal

func (r *Record) Fatal(args ...interface{})

Fatal logs a message at level Fatal

func (*Record) Fatalf

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

Fatal logs a message at level Fatal

func (*Record) Info

func (r *Record) Info(args ...interface{})

Info logs a message at level Info

func (*Record) Infof

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

Info logs a message at level Info

func (*Record) Log

func (r *Record) Log(level Level, args ...interface{})

Log an message with level

func (*Record) Logf

func (r *Record) Logf(level Level, format string, args ...interface{})

Log an message with level

func (*Record) NewBuffer

func (r *Record) NewBuffer() *bytes.Buffer

NewBuffer get or create an Buffer

func (*Record) Notice

func (r *Record) Notice(args ...interface{})

Notice logs a message at level Notice

func (*Record) Noticef

func (r *Record) Noticef(format string, args ...interface{})

Notice logs a message at level Notice

func (*Record) Panic

func (r *Record) Panic(args ...interface{})

Panic logs a message at level Panic

func (*Record) Panicf

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

Panic logs a message at level Panic

func (*Record) SetContext

func (r *Record) SetContext(ctx context.Context) *Record

SetContext on record

func (*Record) SetData

func (r *Record) SetData(data M) *Record

SetData on record

func (*Record) SetExtra

func (r *Record) SetExtra(data M) *Record

SetExtra information on record

func (*Record) SetFields

func (r *Record) SetFields(fields M) *Record

SetFields to the record

func (*Record) SetTime

func (r *Record) SetTime(t time.Time) *Record

SetTime on record

func (*Record) Trace

func (r *Record) Trace(args ...interface{})

Trace logs a message at level Trace

func (*Record) Tracef

func (r *Record) Tracef(format string, args ...interface{})

Trace logs a message at level Trace

func (*Record) WithContext

func (r *Record) WithContext(ctx context.Context) *Record

WithContext on record

func (*Record) WithData

func (r *Record) WithData(data M) *Record

WithData on record

func (*Record) WithError

func (r *Record) WithError(err error) *Record

WithError on record

func (*Record) WithField

func (r *Record) WithField(name string, val interface{}) *Record

WithField with an new field to record

func (*Record) WithFields

func (r *Record) WithFields(fields M) *Record

WithField with new fields to record

func (*Record) WithTime

func (r *Record) WithTime(t time.Time) *Record

WithTime set the record time

type StringMap

type StringMap map[string]string

StringMap string map short name

type SugaredLogger

type SugaredLogger struct {
	*Logger
	// Formatter log message formatter. default use TextFormatter
	Formatter Formatter
	// Output output writer
	Output io.Writer
	// Level for log handling.
	// Greater than or equal to this level will be recorded
	Level Level
}

SugaredLogger definition. Is a fast and usable Logger, which already contains the default formatting and handling capabilities

func NewJSONSugared

func NewJSONSugared(out io.Writer, level Level) *SugaredLogger

NewJSONSugared create new SugaredLogger with JSONFormatter

func NewSugaredLogger

func NewSugaredLogger(output io.Writer, level Level) *SugaredLogger

NewSugaredLogger create new SugaredLogger

func Std

func Std() *SugaredLogger

Std get std logger

func (*SugaredLogger) Close

func (sl *SugaredLogger) Close() error

Close all log handlers

func (*SugaredLogger) Configure

func (sl *SugaredLogger) Configure(fn func(sl *SugaredLogger)) *SugaredLogger

Configure current logger

func (*SugaredLogger) Flush

func (sl *SugaredLogger) Flush() error

Flush all logs

func (*SugaredLogger) Handle

func (sl *SugaredLogger) Handle(record *Record) error

Handle log record

func (*SugaredLogger) IsHandling

func (sl *SugaredLogger) IsHandling(level Level) bool

IsHandling Check if the current level can be handling

func (*SugaredLogger) Reset

func (sl *SugaredLogger) Reset()

Reset the logger

type SyncWriter

type SyncWriter interface {
	Sync() error
	io.Writer
}

SyncWriter is the interface satisfied by logging destinations.

type TextFormatter

type TextFormatter struct {
	// Template text template for render output log messages
	Template string

	// TimeFormat the time format layout. default is time.RFC3339
	TimeFormat string
	// Enable color on print log to terminal
	EnableColor bool
	// ColorTheme setting on render color on terminal
	ColorTheme map[Level]color.Color
	// FullDisplay Whether to display when record.Data, record.Extra, etc. are empty
	FullDisplay bool
	// EncodeFunc data encode for record.Data, record.Extra, etc.
	// Default is encode by `fmt.Sprint()`
	EncodeFunc func(v interface{}) string
	// contains filtered or unexported fields
}

TextFormatter definition

func NewTextFormatter

func NewTextFormatter(template ...string) *TextFormatter

NewTextFormatter create new TextFormatter

func (*TextFormatter) FieldMap

func (f *TextFormatter) FieldMap() StringMap

FieldMap get export field map

func (*TextFormatter) Format

func (f *TextFormatter) Format(r *Record) ([]byte, error)

Format an log record

type WriterHandler

type WriterHandler interface {
	Handler
	Writer() io.Writer
}

WriterHandler is the interface satisfied by logging destinations.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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