logging

package
v1.27.3 Latest Latest
Warning

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

Go to latest
Published: Aug 8, 2023 License: MIT Imports: 10 Imported by: 40

Documentation

Index

Constants

View Source
const CritiLevel = CritLevel

CritiLevel is an alias of CritLevel

Variables

This section is empty.

Functions

func Alert

func Alert(v any)

Alert produce a "Alert" log with the default logger

func Crit

func Crit(v any)

Crit produce a "Critical" log with the default logger

func Debug

func Debug(v any)

Debug produce a "Debug" log with the default logger

func Debugf added in v1.5.2

func Debugf(format string, args ...any)

Debugf produce a "Debug" log in the manner of fmt.Printf with the default logger

func Emerg

func Emerg(v any)

Emerg produce a "Emergency" log with the default logger

func Err

func Err(v any)

Err produce a "Error" log with the default logger

func Fatal

func Fatal(v any)

Fatal produce a "Emergency" log with the default logger and then calls os.Exit(1)

func FprintWithColor

func FprintWithColor(w io.Writer, str string, code ColorType) (int, error)

FprintWithColor formats string with terminal colors and writes to w. It returns the number of bytes written and any write error encountered.

func Info

func Info(v any)

Info produce a "Informational" log with the default logger

func Notice

func Notice(v any)

Notice produce a "Notice" log with the default logger

func Panic

func Panic(v any)

Panic produce a "Emergency" log with the default logger and then calls panic with the message

func Print

func Print(args ...any)

Print produce a log in the manner of fmt.Print with the default logger, without timestamp and log level

func Printf

func Printf(format string, args ...any)

Printf produce a log in the manner of fmt.Printf with the default logger, without timestamp and log level

func Println

func Println(args ...any)

Println produce a log in the manner of fmt.Println with the default logger, without timestamp and log level

func SetLoggerLevel added in v1.19.0

func SetLoggerLevel(logger *Logger, lvl string) error

SetLoggerLevel set a string level to the logger.

func SetTo added in v1.8.8

func SetTo(ctx *gear.Context, key string, val any)

SetTo sets key/value to the Log instance on ctx for the default logger.

app.UseHandler(logging.Default())
app.Use(func(ctx *gear.Context) error {
	logging.SetTo(ctx, "Data", []int{1, 2, 3})
	return ctx.HTML(200, "OK")
})

func Warning

func Warning(v any)

Warning produce a "Warning" log with the default logger

Types

type ColorType

type ColorType uint16

ColorType represents terminal color

const (
	ColorRed     ColorType = 31
	ColorGreen   ColorType = 32
	ColorYellow  ColorType = 33
	ColorBlue    ColorType = 34
	ColorMagenta ColorType = 35
	ColorCyan    ColorType = 36
	ColorWhite   ColorType = 37
	ColorGray    ColorType = 90
)

Color Code https://en.wikipedia.org/wiki/ANSI_escape_code 30–37: set text color to one of the colors 0 to 7, 40–47: set background color to one of the colors 0 to 7, 39: reset text color to default, 49: reset background color to default, 1: make text bold / bright (this is the standard way to access the bright color variants), 22: turn off bold / bright effect, and 0: reset all text properties (color, background, brightness, etc.) to their default values. For example, one could select bright purple text on a green background (eww!) with the code `\x1B[35;1;42m`

type Level

type Level uint8

Level represents logging level https://tools.ietf.org/html/rfc5424 https://en.wikipedia.org/wiki/Syslog

const (
	// EmergLevel is 0, "Emergency", system is unusable
	EmergLevel Level = iota
	// AlertLevel is 1, "Alert", action must be taken immediately
	AlertLevel
	// CritLevel is 2, "Critical", critical conditions
	CritLevel
	// ErrLevel is 3, "Error", error conditions
	ErrLevel
	// WarningLevel is 4, "Warning", warning conditions
	WarningLevel
	// NoticeLevel is 5, "Notice", normal but significant condition
	NoticeLevel
	// InfoLevel is 6, "Informational", informational messages
	InfoLevel
	// DebugLevel is 7, "Debug", debug-level messages
	DebugLevel
)

func ParseLevel added in v1.10.1

func ParseLevel(lvl string) (Level, error)

ParseLevel takes a string level and returns the gear logging level constant.

func (Level) String added in v1.9.1

func (l Level) String() string

https://en.wikipedia.org/wiki/Syslog

type Log

type Log map[string]any

Log records key-value pairs for structured logging.

func FromCtx

func FromCtx(ctx *gear.Context) Log

FromCtx retrieve the Log instance for the default logger.

func (Log) Format added in v1.7.0

func (l Log) Format() (string, error)

Format try to marshal the structured log with json.Marshal.

func (Log) From added in v1.7.0

func (l Log) From(log Log) Log

From copy values from the Log argument, returns self.

log := Log{"key": "foo"}
logging.Info(log.From(Log{"key2": "foo2"}))

func (Log) GoString added in v1.7.0

func (l Log) GoString() string

GoString implemented fmt.GoStringer interface, returns a Go-syntax string.

func (Log) Into added in v1.7.0

func (l Log) Into(log Log) Log

Into copy self values into the Log argument, returns the Log argument.

redisLog := Log{"kind": "redis"}
logging.Err(redisLog.Into(Log{"data": "foo"}))

func (Log) KV added in v1.24.2

func (l Log) KV(key string, value any) Log

KV set key/value to the log, returns self.

log := Log{}
logging.Info(log.KV("key1", "foo").KV("key2", 123))

func (Log) Reset added in v0.19.0

func (l Log) Reset()

Reset delete all key-value on the log. Empty log will not be consumed.

log := logger.FromCtx(ctx)
if ctx.Path == "/" {
	log.Reset() // reset log, don't logging for path "/"
} else {
	log["data"] = someData
}

func (Log) String added in v0.20.2

func (l Log) String() string

String implemented fmt.Stringer interface, returns a Go-syntax string.

func (Log) With added in v1.8.5

func (l Log) With(log map[string]any) Log

With copy values from the argument, returns new log.

log := Log{"key": "foo"}
logging.Info(log.With(Log{"key2": "foo2"}))

type Logger

type Logger struct {
	// Destination for output, It's common to set this to a
	// file, or `os.Stderr`. You can also set this to
	// something more adventorous, such as logging to Kafka.
	Out io.Writer
	// contains filtered or unexported fields
}

A Logger represents an active logging object that generates lines of output to an io.Writer. Each logging operation makes a single call to the Writer's Write method. A Logger can be used simultaneously from multiple goroutines; it guarantees to serialize access to the Writer.

A custom logger example:

app := gear.New()

logger := logging.New(os.Stdout)
logger.SetLevel(logging.InfoLevel)
logger.SetLogInit(func(log logging.Log, ctx *gear.Context) {
  log["ip"] = ctx.IP().String()
  log["method"] = ctx.Method
  log["uri"] = ctx.Req.RequestURI
  log["proto"] = ctx.Req.Proto
  log["userAgent"] = ctx.GetHeader(gear.HeaderUserAgent)
  log["start"] = ctx.StartAt.Format("2006-01-02T15:04:05.000Z")
  if s := ctx.GetHeader(gear.HeaderOrigin); s != "" {
  	log["origin"] = s
  }
  if s := ctx.GetHeader(gear.HeaderReferer); s != "" {
  	log["referer"] = s
  }
})
logger.SetLogConsume(func(log logging.Log, _ *gear.Context) {
	end := time.Now().UTC()
	if str, err := log.Format(); err == nil {
		logger.Output(end, logging.InfoLevel, str)
	} else {
		logger.Output(end, logging.WarningLevel, log.String())
	}
})

app.UseHandler(logger)
app.Use(func(ctx *gear.Context) error {
	log := logger.FromCtx(ctx)
	log["data"] = []int{1, 2, 3}
	return ctx.HTML(200, "OK")
})

func Default

func Default(devMode ...bool) *Logger

Default returns the default logger If devMode is true, logger will print a simple version of Common Log Format with terminal color

func New

func New(w io.Writer) *Logger

New creates a Logger instance with given io.Writer and DebugLevel log level. the logger timestamp format is "2006-01-02T15:04:05.000Z"(JavaScript ISO date string), log format is "[%s] %s %s"

func (*Logger) Alert

func (l *Logger) Alert(v any)

Alert produce a "Alert" log

func (*Logger) Crit

func (l *Logger) Crit(v any)

Crit produce a "Critical" log

func (*Logger) Debug

func (l *Logger) Debug(v any)

Debug produce a "Debug" log

func (*Logger) Debugf added in v1.5.2

func (l *Logger) Debugf(format string, args ...any)

Debugf produce a "Debug" log in the manner of fmt.Printf

func (*Logger) Emerg

func (l *Logger) Emerg(v any)

Emerg produce a "Emergency" log

func (*Logger) Err

func (l *Logger) Err(v any)

Err produce a "Error" log

func (*Logger) Fatal

func (l *Logger) Fatal(v any)

Fatal produce a "Emergency" log and then calls os.Exit(1)

func (*Logger) FromCtx

func (l *Logger) FromCtx(ctx *gear.Context) Log

FromCtx retrieve the Log instance from the ctx with ctx.Any. Logger.New and ctx.Any will guarantee it exists.

func (*Logger) GetLevel added in v1.10.1

func (l *Logger) GetLevel() Level

GetLevel get the logger's log level

func (*Logger) Info

func (l *Logger) Info(v any)

Info produce a "Informational" log

func (*Logger) New

func (l *Logger) New(ctx *gear.Context) (any, error)

New implements gear.Any interface,then we can use ctx.Any to retrieve a Log instance from ctx. Here also some initialization work after created.

func (*Logger) Notice

func (l *Logger) Notice(v any)

Notice produce a "Notice" log

func (*Logger) Output

func (l *Logger) Output(t time.Time, level Level, s string) (err error)

Output writes a string log with timestamp and log level to the output. The log will be format by timeFormat and logFormat.

func (*Logger) OutputJSON added in v1.16.0

func (l *Logger) OutputJSON(log Log) (err error)

OutputJSON writes a Log log as JSON string to the output.

func (*Logger) Panic

func (l *Logger) Panic(v any)

Panic produce a "Emergency" log and then calls panic with the message

func (*Logger) Print

func (l *Logger) Print(args ...any)

Print produce a log in the manner of fmt.Print, without timestamp and log level

func (*Logger) Printf

func (l *Logger) Printf(format string, args ...any)

Printf produce a log in the manner of fmt.Printf, without timestamp and log level

func (*Logger) Println

func (l *Logger) Println(args ...any)

Println produce a log in the manner of fmt.Println, without timestamp and log level

func (*Logger) Serve

func (l *Logger) Serve(ctx *gear.Context) error

Serve implements gear.Handler interface, we can use logger as gear middleware.

app := gear.New()
app.UseHandler(logging.Default())
app.Use(func(ctx *gear.Context) error {
	log := logging.FromCtx(ctx)
	log["data"] = []int{1, 2, 3}
	return ctx.HTML(200, "OK")
})

func (*Logger) SetJSONLog added in v1.16.0

func (l *Logger) SetJSONLog() *Logger

SetJSONLog set the logger writing JSON string log. It will become default in Gear@v2.

func (*Logger) SetLevel

func (l *Logger) SetLevel(level Level) *Logger

SetLevel set the logger's log level The default logger level is DebugLevel

func (*Logger) SetLogConsume added in v0.19.0

func (l *Logger) SetLogConsume(fn func(Log, *gear.Context)) *Logger

SetLogConsume set a log consumer handle to the logger. It will be called on a "end hook" and should write the log to underlayer logging system. The default implements is for development, the output log format:

127.0.0.1 GET /text 200 6500 - 0.765 ms

Please implements a Log Consume for your production.

func (*Logger) SetLogFormat

func (l *Logger) SetLogFormat(logFormat string) *Logger

SetLogFormat set the logger log format it should accept 3 string values: timestamp, log level and log message The default logger log format is "[%s] %s %s": "time logLevel message"

func (*Logger) SetLogInit added in v0.19.0

func (l *Logger) SetLogInit(fn func(Log, *gear.Context)) *Logger

SetLogInit set a log init handle to the logger. It will be called when log created.

func (*Logger) SetTimeFormat

func (l *Logger) SetTimeFormat(timeFormat string) *Logger

SetTimeFormat set the logger timestamp format The default logger timestamp format is "2006-01-02T15:04:05.000Z"(JavaScript ISO date string)

func (*Logger) SetTo added in v1.8.8

func (l *Logger) SetTo(ctx *gear.Context, key string, val any)

SetTo sets key/value to the Log instance on ctx.

app.Use(func(ctx *gear.Context) error {
	logging.SetTo(ctx, "Data", []int{1, 2, 3})
	return ctx.HTML(200, "OK")
})

func (*Logger) Warning

func (l *Logger) Warning(v any)

Warning produce a "Warning" log

type Messager added in v1.7.0

type Messager interface {
	fmt.Stringer
	Format() (string, error)
}

Messager is implemented by any value that has a Format method and a String method. They are using by Logger to format value to string.

Jump to

Keyboard shortcuts

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