log

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: May 7, 2022 License: MIT Imports: 6 Imported by: 0

README

说明

基于 zap 封装的日志库,只封装了一些常用的操作。

使用

包级函数直接调用,支持 DebugInfoWarnErrorFatal 五种级别日志。

package main

import (
	"github.com/fengh0409/log"
)

func main() {
	defer log.Sync()
	log.Debug("this is debug level log")
	log.Info("this is info level log", " more args")
	log.Warn("this is warn level log")
	log.Error("this is error level log")
	//log.Fatal("this is fatal level log") // will exit
	log.Debugf("this is %s level log", "debugf")
	log.Infof("this is %s level log", "infof")
	log.Warnf("this is %s level log", "warnf")
	log.Errorf("this is %s level log", "errorf")
	//log.Fatalf("this is %s level log", "fatalf") //will exit
}

输出:

2022-04-29T22:02:42.744+0800	INFO	mytest/main.go:10	this is info level log more args
2022-04-29T22:02:42.744+0800	WARN	mytest/main.go:11	this is warn level log
2022-04-29T22:02:42.744+0800	ERROR	mytest/main.go:12	this is error level log
2022-04-29T22:02:42.744+0800	INFO	mytest/main.go:15	this is infof level log
2022-04-29T22:02:42.744+0800	WARN	mytest/main.go:16	this is warnf level log
2022-04-29T22:02:42.744+0800	ERROR	mytest/main.go:17	this is errorf level log

默认只会显示 Info 及以上级别的日志,若要显示 Debug 或其他级别的日志,请调用 log.SetOptions(log.WithLevel(log.DebugLevel)),例如:

package main

import (
	"github.com/fengh0409/log"
)

func main() {
	defer log.Sync()
	log.SetOptions(log.WithLevel(log.DebugLevel))
	// 以上 log.DebugLevel 是 int 类型,若是命令行参数传进来的字符串,如 info,使用以下方式:
	// log.SetOptions(log.WithLevelString("debug"))

	log.Debug("this is debug level log")
	log.Info("this is info level log")
}

输出:

2022-04-29T22:04:19.204+0800	DEBUG	mytest/main.go:11	this is debug level log
2022-04-29T22:04:19.205+0800	INFO	mytest/main.go:12	this is info level log

日志写入文件

默认情况下,日志写入到标准错误输出,若要写入文件,请调用 log.SetOptions(log.WithFileWriter())

package main

import (
	"github.com/fengh0409/log"
)

func main() {
	defer log.Sync()
	log.SetOptions(log.WithFileWriter(log.WithFilename("/tmp/mytest.log")))

	log.Info("show some message")
	log.Error("show some error message")
}

查看 /tmp/mytest.log 文件内容:

2022-05-05T21:31:11.680+0800	INFO	mytest/main.go:11	show some message
2022-05-05T21:31:11.681+0800	ERROR	mytest/main.go:12	show some error message

日志文件支持自动切割,log.WithFileWriter() 可以传入以下函数进行配置:

  • log.WithFilename("/tmp/log/lumberjack.log") 设置日志文件名,默认写入到 /tmp/log/lumberjack.log
  • log.WithMaxSize(200) 设置日志文件最大容量,单位 MB,默认 200MB
  • log.WithMaxAge(7) 设置日志文件保留最长时间,单位 天,默认 7 天
  • log.WithBackups(10) 设置日志文件最大个数,默认 10 个
  • log.WithCompress(true) 设置是否压缩归档的日志文件,默认是

结构化日志

输出 json 格式的结构化日志,输出到标准输出,打印 Info 及以上级别日志。

package main

import (
	"os"

	"github.com/fengh0409/log"
)

func main() {
	logger := log.New(
		log.WithWriter(os.Stdout),
		log.WithEncoding("json"),
	).Build()
	defer logger.Sync()

	logger.Info("show some message", log.String("hello", "world"))
	logger.Error("show some error message", log.Int("code", 404))
}

输出:

{"level":"info","ts":1651757350.029574,"caller":"mytest/main.go:16","msg":"show some message","hello":"world"}
{"level":"error","ts":1651757350.0296729,"caller":"mytest/main.go:17","msg":"show some error message","code":404}

Documentation

Index

Constants

View Source
const (
	// ConsoleEncoder output the log with console
	ConsoleEncoder = "console"
	// JSONEncoder output the log with json format
	JSONEncoder = "json"
)

Variables

View Source
var (
	// Any is alias of zap.Any Field
	Any = zap.Any
	// Bool is alias of zap.Bool Field
	Bool = zap.Bool
	// String is alias of zap.String Field
	String = zap.String
	// Float32 alias of zap.Float32 Field
	Float32 = zap.Float32
	// Float64 is alias of zap.Float64 Field
	Float64 = zap.Float64
	// Int is alias of zap.Int Field
	Int = zap.Int
	// Int8 is alias of zap.Int8 Field
	Int8 = zap.Int8
	// Int16 is alias of zap.Intl6 Field
	Int16 = zap.Int16
	// Int32 is alias of zap.Int32 Field
	Int32 = zap.Int32
	// Int64 is alias of zap.Int64 Field
	Int64 = zap.Int64
	// Uint is alias of zap.Uint Field
	Uint = zap.Uint
	// Uint8 is alias of zap.Uint8 Field
	Uint8 = zap.Uint8
	// Vint16 is alias of zap.Uintl6 Field
	Uint16 = zap.Uint16
	// Uint32 is alias of zap.Uint32 Field
	Uint32 = zap.Uint32
	// Uint64 is alias of zap.Uint64 Field
	Uint64 = zap.Uint64
	// Namespace is alias of zap.Namespace Field
	Namespace = zap.Namespace
)

Functions

func Debug

func Debug(args ...interface{})

Debug logs a message at level Debug on the standard logger

func Debugf

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

Debugf logs a message at level Debug on the standard loggero

func Error

func Error(args ...interface{})

Error logs a message at level Error on the standard loggero

func Errorf

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

Errorf logs a message at level Error on the standard loggero

func Fatal

func Fatal(args ...interface{})

Fatal logs a message at level Fatal on the standard loggero

func Fatalf

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

Fatalf logs a message at level Fatal on the standard loggero

func Info

func Info(args ...interface{})

Info logs a message at level Info on the standard logger

func Infof

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

Infof logs a message at level Info on the standard loggero

func SetOptions

func SetOptions(options ...Option)

SetOptions set options

func Sync

func Sync() error

Sync calls the sugar's Sync method

func Warn

func Warn(args ...interface{})

Warn logs a message at level Warn on the standard loggero

func Warnf

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

Warnf logs a message at level Warn on the standard loggero

Types

type Field

type Field = zap.Field

Field is alias of zap.Field

type FileOption

type FileOption func(*FileOptions)

FileOption define a func wraps FileOptions

func WithCompress

func WithCompress(compress bool) FileOption

WithCompress specify if the rotated files should be compressed using gzip

func WithFilename

func WithFilename(filename string) FileOption

WithFilename specify the filename where log to write

func WithMaxAge

func WithMaxAge(maxAge int) FileOption

WithMaxAge specify the maximum number days to retain old files based on the timestamp encoded in their filename

func WithMaxBackups

func WithMaxBackups(maxBackups int) FileOption

WithMaxBackups specify the maximum number of old log files to retain

func WithMaxSize

func WithMaxSize(maxSize int) FileOption

WithMaxSize specify maximum size in MB of the file before it gets rotated

type FileOptions

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

FileOptions define the file writer options

type Level

type Level = zapcore.Level

Level is alias of zapcore.Level

const (
	// DebugLevel logs are typically voluminous, and are usually disabled in production.
	DebugLevel Level = zap.DebugLevel
	// InfoLevel is the default logging priority.
	InfoLevel Level = zap.InfoLevel
	// WarnLevel logs are more important than Info, but don't need individual human review.
	WarnLevel Level = zap.WarnLevel
	// ErrorLevel logs are high-priority. If an application is running smoothly,
	// it shouldn't generate any error-level logs.
	ErrorLevel Level = zap.ErrorLevel
	// FatalLevel logs a message, then calls os.Exit(1).
	FatalLevel Level = zap.FatalLevel
)

type Log

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

Log wraps zap logger

func (*Log) Debug

func (l *Log) Debug(msg string, fields ...Field)

Debug logs a message at DebugLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Log) Error

func (l *Log) Error(msg string, fields ...Field)

Error logs a message at ErrorLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Log) Fatal

func (l *Log) Fatal(msg string, fields ...Field)

Fatal logs a message at FatalLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Log) Info

func (l *Log) Info(msg string, fields ...Field)

Info logs a message at InfoLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Log) Sugar

func (l *Log) Sugar() *SugaredLogger

Sugar calls the logger's Sugar method

func (*Log) Sync

func (l *Log) Sync() error

Sync calls the logger's Sync method

func (*Log) Warn

func (l *Log) Warn(msg string, fields ...Field)

Warn logs a message at WarnLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

type Logger

type Logger = zap.Logger

Logger is alias of zap.Logger

type Option

type Option func(*Options)

Option define a func wraps Options

func WithEncoding

func WithEncoding(encoding string) Option

WithEncoding specify the format of output, "json" and "console" are supported

func WithFileWriter

func WithFileWriter(options ...FileOption) Option

WithFileWriter support write log to local file, with the FileOption configures

func WithLevel

func WithLevel(level Level) Option

withLevel specify the log level

func WithLevelString

func WithLevelString(levelString string) Option

withLevelString convert the level to Level type, if not exists, we set it as InfoLevel default

func WithWriter

func WithWriter(writer io.Writer) Option

WithWriter specify the writer where log to write

type Options

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

Options define some options for building a Log

func New

func New(options ...Option) *Options

New initialize the options for building

func (*Options) Build

func (o *Options) Build() *Log

Build construct a Log from Options

type SugaredLogger

type SugaredLogger = zap.SugaredLogger

Sugaredlogger is alias of zap.Sugaredlogger

Jump to

Keyboard shortcuts

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