slog

package module
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2022 License: MIT Imports: 17 Imported by: 0

README

slog

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

📑 Lightweight, extensible, configurable logging library written in Go

中文说明

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

Features

  • Simple, directly available without configuration
  • Support common log level processing. eg: trace debug info notice warn error fatal panic
  • Supports adding multiple Handler log processing at the same time, outputting logs to different places
  • Support any extension of Handler Formatter as needed
  • Support to custom log messages Handler
  • Support to custom log message Formatter
    • Built-in json text two log record formatting Formatter
  • Has built-in common log write processing program
    • console output logs to the console, supports color output
    • stream output logs to the specified io.Writer
    • simple_file output logs to file, no buffer Write directly to file
    • file output logs to file. By default, buffer is enabled.
    • size_rotate_file output logs to file, and supports rotating files by size. By default, buffer is enabled.
    • time_rotate_file output logs to file, and supports rotating files by time. By default, buffer is enabled.
    • rotate_file output logs to file, and supports rotating files by time and size. By default, buffer is enabled.

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"}

Logs to file

  • FileHandler output logs to file. By default, buffer is enabled.
    • default buffer size is 256 * 1024
package mypkg

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

func myfunc() {
	defer slog.Flush()

	h1 := handler.MustFileHandler("/tmp/error.log", true)
	h1.Levels = slog.Levels{slog.PanicLevel, slog.ErrorLevel, slog.WarnLevel}

	h2 := handler.MustFileHandler("/tmp/info.log", true)
	h2.Levels = slog.Levels{slog.InfoLevel, slog.NoticeLevel, slog.DebugLevel, slog.TraceLevel}

	slog.PushHandler(h1)
	slog.PushHandler(h2)

	// add logs
	slog.Info("info message text")
	slog.Error("error message text")
}

How to use handler

Create handler
h1, err := handler.NewSimpleFile("info.log")

h2, err := handler.NewFileHandler("error.log")

h3, err := handler.NewFileHandler("error.log")
Push handler to logger
	// append to logger
	l := slog.PushHandler(h)

	// logging messages
	slog.Info("info message")
	slog.Warn("warn message")
New logger with handlers
	// for new logger
	l := slog.NewWithHandlers(h1, h2)

	// logging messages
	l.Info("info message")
	l.Warn("warn message")

Built-in Handlers

BufferedHandler

BufferedHandler - can wrapper an io.WriteCloser as an slog.Handler

package mypkg
import (
	"github.com/gookit/slog"
	"github.com/gookit/slog/handler"
	"github.com/stretchr/testify/assert"
)

func myfunc() {
	fpath := "./testdata/buffered-os-file.log"

	file, err := handler.QuickOpenFile(fpath)
	assert.NoError(t, err)

	bh := handler.NewBuffered(file, 2048)

	// new logger
	l := slog.NewWithHandlers(bh)

	// logging messages
	l.Info("buffered info message")
	l.Warn("buffered warn message")
}
ConsoleHandler

ConsoleHandler - output logs to the console terminal. support color by gookit/color.

Create:

func NewConsoleHandler(levels []slog.Level) *ConsoleHandler
EmailHandler

NewEmailHandler - output logs to email.

Create:

h := handler.NewEmailHandler(from EmailOption, toAddresses []string)
RotateFileHandler

RotateFileHandler - output log messages to file.

Create:

func NewRotateFile(filepath string) (*RotateFileHandler, error)
func NewRotateFileHandler(filepath string) (*RotateFileHandler, error)
TimeRotateFileHandler

TimeRotateFileHandler - output log messages to file.

Create:

func NewTimeRotateFile(filepath string) (*TimeRotateFileHandler, error)
func NewTimeRotateFileHandler(filepath string) (*TimeRotateFileHandler, error)

The rotating files format support:

const (
	EveryDay rotateTime = iota
	EveryHour
	Every30Minutes
	Every15Minutes
	EveryMinute
	EverySecond // only use for tests
)

file examples:

time-rotate-file.log
time-rotate-file.log.20201229_155753
time-rotate-file.log.20201229_155754
SizeRotateFileHandler

SizeRotateFileHandler - output log messages to file.

Create:

func NewSizeRotateFile(filepath string) (*SizeRotateFileHandler, error)
func NewSizeRotateFileHandler(filepath string) (*SizeRotateFileHandler, error)

The rotating files format is filename.log.yMD_0000N. such as:

size-rotate-file.log
size-rotate-file.log.122915_00001
size-rotate-file.log.122915_00002
SimpleFileHandler

SimpleFileHandler - direct write log messages to a file. Not recommended for production environment

Create:

func NewSimpleFile(filepath string) (*SimpleFileHandler, error)
func NewSimpleFileHandler(filepath string) (*SimpleFileHandler, error)

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)

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

JSON Formatter

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
}

Text Formatter

default templates:

const DefaultTemplate = "[{{datetime}}] [{{channel}}] [{{level}}] [{{caller}}] {{message}} {{data}} {{extra}}\n"
const NamedTemplate = "{{datetime}} channel={{channel}} level={{level}} [file={{caller}}] message={{message}} data={{data}}\n"

Gookit packages

  • gookit/ini Go config management, use INI files
  • gookit/rux Simple and fast request router for golang HTTP
  • gookit/gcli Build CLI application, tool library, running CLI commands
  • gookit/slog Lightweight, extensible, configurable logging library written in Go
  • gookit/color A command-line color library with true color support, universal API methods and Windows support
  • gookit/event Lightweight event manager and dispatcher implements by Go
  • gookit/cache Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached.
  • gookit/config Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags
  • gookit/filter Provide filtering, sanitizing, and conversion of golang data
  • gookit/validate Use for data validation and filtering. support Map, Struct, Form data
  • gookit/goutil Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more
  • More, please see https://github.com/gookit

Acknowledgment

The projects is heavily inspired by follow packages:

LICENSE

MIT

Documentation

Overview

Package slog Lightweight, extensible, configurable logging library written in 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.

Example (ConfigSlog)
package main

import (
	"github.com/tomorrowsky/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:

Example (QuickStart)
package main

import (
	"github.com/tomorrowsky/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:

Example (UseJSONFormat)
package main

import (
	"github.com/tomorrowsky/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:

Index

Examples

Constants

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 (
	FieldKeyTime = "time"

	// FieldKeyData = "data"
	FieldKeyData = "data"

	// FieldKeyCaller filename with line with func name. eg: "logger_test.go:48->TestLogger_ReportCaller"
	FieldKeyCaller = "caller"
	// FieldKeyFLine filename with line. eg: "logger_test.go:48"
	FieldKeyFLine = "fline"
	// FieldKeyPkg package name. "github.com/gookit/slog_test"
	FieldKeyPkg = "package"
	// FieldKeyFunc package with func name. eg: "github.com/gookit/slog_test.TestLogger_ReportCaller"
	FieldKeyFunc = "func"
	// FieldKeyFunc only func name. eg: "TestLogger_ReportCaller"
	FieldKeyFcName = "fcname"
	// FieldKeyFile full filepath with line. eg: "/work/go/gookit/slog/logger_test.go:48"
	FieldKeyFile = "file"

	FieldKeyDatetime  = "datetime"
	FieldKeyTimestamp = "timestamp"

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

	FieldKeyChannel = "channel"
	FieldKeyMessage = "message"
)
View Source
var (
	DefaultChannelName = "application"
	DefaultTimeFormat  = "2006/01/02 15:04:05"
)
View Source
var (
	// AllLevels exposing all logging levels
	AllLevels = Levels{
		PanicLevel,
		FatalLevel,
		ErrorLevel,
		WarnLevel,
		NoticeLevel,
		InfoLevel,
		DebugLevel,
		TraceLevel,
	}

	DangerLevels = Levels{PanicLevel, FatalLevel, ErrorLevel, WarnLevel}
	NormalLevels = Levels{InfoLevel, NoticeLevel, DebugLevel, TraceLevel}

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

	// 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 DoNothingOnExit = func(code int) {

}

DoNothingOnExit handler. use for testing.

View Source
var (
	// ErrorKey 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))

Configure the std logger

func Debug

func Debug(args ...interface{})

Debug logs a message at level Debug

func Debugf

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

Debugf logs a message at level Debug

func EncodeToString

func EncodeToString(v interface{}) string

EncodeToString data to string

func Error

func Error(args ...interface{})

Error logs a message at level Error

func ErrorT

func ErrorT(err error)

ErrorT logs a error type at level Error

func Errorf

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

Errorf 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{})

Fatalf logs a message at level Fatal

func Flush

func Flush() error

Flush log messages

func FlushDaemon

func FlushDaemon()

FlushDaemon run flush handle on daemon

Usage:

go slog.FlushDaemon()

func FlushTimeout

func FlushTimeout(timeout time.Duration)

FlushTimeout flush logs with timeout.

func Info

func Info(args ...interface{})

Info logs a message at level Info

func Infof

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

Infof 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{})

Noticef logs a message at level Notice

func Panic

func Panic(args ...interface{})

Panic logs a message at level Panic

func Panicf

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

Panicf logs a message at level Panic

func PrependExitHandler

func PrependExitHandler(handler func())

PrependExitHandler prepend register an exit-handler on global exitHandlers

func Print

func Print(args ...interface{})

Print logs a message at level PrintLevel

func Printf

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

Printf logs a message at level PrintLevel

func Println

func Println(args ...interface{})

Println logs a message at level PrintLevel

func PushHandler

func PushHandler(h Handler)

PushHandler to the std logger

func PushHandlers

func PushHandlers(hs ...Handler)

PushHandlers to the std logger

func RegisterExitHandler

func RegisterExitHandler(handler func())

RegisterExitHandler 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 SetLogLevel

func SetLogLevel(l Level)

SetLogLevel for the std logger

func Trace

func Trace(args ...interface{})

Trace logs a message at level Trace

func Tracef

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

Tracef 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{})

Warnf logs a message at level Warn

Types

type FlushCloseWriter

type FlushCloseWriter interface {
	Flush() error
	// WriteCloser the output writer
	io.WriteCloser
}

FlushCloseWriter is the interface satisfied by logging destinations.

type Formattable

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

Formattable definition

func (*Formattable) FormatRecord

func (f *Formattable) FormatRecord(record *Record) ([]byte, error)

FormatRecord to bytes

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 you can format record and write result to record.Buffer
	Format(record *Record) ([]byte, error)
}

Formatter interface

func GetFormatter

func GetFormatter() Formatter

GetFormatter of the std logger

type FormatterFunc

type FormatterFunc func(r *Record) error

FormatterFunc wrapper definition

func (FormatterFunc) Format

func (fn FormatterFunc) Format(r *Record) error

Format an record

type FormatterWriterHandler

type FormatterWriterHandler interface {
	Handler
	// Formatter record formatter
	Formatter() Formatter
	// Writer the output writer
	Writer() io.Writer
}

FormatterWriterHandler interface

type Handler

type Handler interface {
	// Closer Close handler.
	// You should first call Flush() on close logic.
	// Refer the FileHandler.Close() handle
	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 MustLevelByName

func MustLevelByName(ln string) Level

MustLevelByName convert name to level

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

func (l Level) ShouldHandling(curLevel Level) bool

ShouldHandling compare level

func (Level) String

func (l Level) String() string

String get level name

type Levels

type Levels []Level

Levels level list

func (Levels) Contains

func (ls Levels) Contains(level Level) bool

Contains given level

type Logger

type Logger struct {

	// options
	// ReportCaller on log message
	ReportCaller   bool
	LowerLevelName bool
	MaxCallerDepth int

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

Logger definition. The logger implements the `github.com/gookit/gsr.Logger`

func New

func New() *Logger

New create an new logger

Example
package main

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

func main() {
	mylog := slog.New()
	mylog.AddHandler(handler.MustFileHandler("app.log", false))

	mylog.Info("info log message")
	mylog.Warn("warning log message")
	mylog.Infof("info log %s", "message")
}
Output:

func NewWithConfig

func NewWithConfig(fn func(l *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 (l *Logger) AddHandler(h Handler)

AddHandler to the logger

func (*Logger) AddHandlers

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

AddHandlers to the logger

func (*Logger) AddProcessor

func (l *Logger) AddProcessor(p Processor)

AddProcessor to the logger

func (*Logger) AddProcessors

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

AddProcessors to the logger

func (*Logger) Close

func (l *Logger) Close()

Close the logger

func (*Logger) Configure

func (l *Logger) Configure(fn func(l *Logger)) *Logger

Configure current logger

func (*Logger) Debug

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

Debug logs a message at level Debug

func (*Logger) Debugf

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

Debugf logs a message at level Debug

func (*Logger) Error

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

Error logs a message at level error

func (*Logger) ErrorT

func (l *Logger) ErrorT(err error)

ErrorT logs a error type at level Error

func (*Logger) Errorf

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

Errorf logs a message at level Error

func (*Logger) Exit

func (l *Logger) Exit(code int)

Exit logger handle

func (*Logger) ExitHandlers

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

ExitHandlers get all exitHandlers of the logger

func (*Logger) Fatal

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

Fatal logs a message at level Fatal

func (*Logger) Fatalf

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

Fatalf logs a message at level Fatal

func (*Logger) Fatalln

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

Fatalln logs a message at level Fatal

func (*Logger) Flush

func (l *Logger) Flush()

Flush flushes all the logs to disk. alias of the FlushAll()

func (*Logger) FlushAll

func (l *Logger) FlushAll()

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

func (*Logger) FlushDaemon

func (l *Logger) FlushDaemon()

FlushDaemon run flush handle on daemon

Usage:

go slog.FlushDaemon()

func (*Logger) FlushTimeout

func (l *Logger) FlushTimeout(timeout time.Duration)

FlushTimeout flush logs on limit time. refer from glog package

func (*Logger) Info

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

Info logs a message at level Info

func (*Logger) Infof

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

Infof logs a message at level Info

func (*Logger) Log

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

Log an message

func (*Logger) Logf

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

Logf an message

func (*Logger) Name

func (l *Logger) Name() string

Name of the logger

func (*Logger) Notice

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

Notice logs a message at level Notice

func (*Logger) Noticef

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

Noticef logs a message at level Notice

func (*Logger) Panic

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

Panic logs a message at level Panic

func (*Logger) Panicf

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

Panicf logs a message at level Panic

func (*Logger) Panicln

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

Panicln logs a message at level Panic

func (*Logger) PrependExitHandler

func (l *Logger) PrependExitHandler(handler func())

PrependExitHandler prepend register an exit-handler on global exitHandlers

func (*Logger) Print

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

Print logs a message at level PrintLevel

func (*Logger) Printf

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

Printf logs a message at level PrintLevel

func (*Logger) Println

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

Println logs a message at level PrintLevel

func (*Logger) PushHandler

func (l *Logger) PushHandler(h Handler)

PushHandler to the l. alias of AddHandler()

func (*Logger) PushHandlers

func (l *Logger) PushHandlers(hs ...Handler)

PushHandlers to the logger

func (*Logger) PushProcessor

func (l *Logger) PushProcessor(p Processor)

PushProcessor to the logger alias of AddProcessor()

func (*Logger) RegisterExitHandler

func (l *Logger) RegisterExitHandler(handler func())

RegisterExitHandler register an exit-handler on global exitHandlers

func (*Logger) Reset

func (l *Logger) Reset()

Reset the logger

func (*Logger) ResetExitHandlers

func (l *Logger) ResetExitHandlers()

ResetExitHandlers reset logger exitHandlers

func (*Logger) ResetHandlers

func (l *Logger) ResetHandlers()

ResetHandlers for the logger

func (*Logger) ResetProcessors

func (l *Logger) ResetProcessors()

ResetProcessors for the logger

func (*Logger) SetHandlers

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

SetHandlers for the logger

func (*Logger) SetName

func (l *Logger) SetName(name string)

SetName for logger

func (*Logger) SetProcessors

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

SetProcessors for the logger

func (*Logger) Sync

func (l *Logger) Sync() error

Sync flushes buffered logs (if any).

func (*Logger) Trace

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

Trace logs a message at level Trace

func (*Logger) Tracef

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

Tracef logs a message at level Trace

func (*Logger) VisitAll

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

VisitAll logger handlers

func (*Logger) Warn

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

Warn logs a message at level Warn

func (*Logger) Warnf

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

Warnf logs a message at level Warn

func (*Logger) Warning

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

Warning logs a message at level Warn

func (*Logger) WithContext

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

WithContext new record with context.Context

func (*Logger) WithData

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

WithData new record with data

func (*Logger) WithFields

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

WithFields new record with fields

func (*Logger) WithTime

func (l *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{}

func (M) String

func (m M) String() string

String map to string

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)
	// ProcessRecord handle an record
	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

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.SetExtraValue("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

	// 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 data.
	// Contains all the fields set by the user.
	Fields M

	// Data log context 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{})

Debugf 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{})

Errorf 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{})

Fatalf logs a message at level Fatal

func (*Record) Fatalln

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

Fatalln 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{})

Infof logs a message at level Info

func (*Record) LevelName

func (r *Record) LevelName() string

LevelName get

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{})

Logf an message with level

func (*Record) MicroSecond

func (r *Record) MicroSecond() int

MicroSecond of the record

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{})

Noticef 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{})

Panicf logs a message at level Panic

func (*Record) Panicln

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

Panicln logs a message at level Panic

func (*Record) Print

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

Print logs a message at level Print

func (*Record) Printf

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

Printf logs a message at level Print

func (*Record) Println

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

Println logs a message at level Print

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

func (r *Record) SetExtraValue(k string, v interface{})

SetExtraValue 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{})

Tracef 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

WithFields 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 NewStdLogger

func NewStdLogger() *SugaredLogger

NewStdLogger instance

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

FlushAll all logs. alias of the FlushAll()

func (*SugaredLogger) FlushAll

func (sl *SugaredLogger) FlushAll() 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 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

func (*TextFormatter) SetTemplate

func (f *TextFormatter) SetTemplate(fmtTpl string)

SetTemplate set the log format template and update field-map

Directories

Path Synopsis
Package handler provide useful common log handlers.
Package handler provide useful common log handlers.

Jump to

Keyboard shortcuts

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