logger

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2022 License: MIT Imports: 8 Imported by: 0

README

介绍

此日志组件是对 zap 组件的简单封装,增加了日志写入到文件,日志文件按照大小循环等可配置项,简化使用。

使用方式

package main

import (
 "fmt"
 "github.com/binary4cat/logger"
 "time"
)

func main() {
 opt := logger.Options{
  NotStdout:  false,          // 不要输出到标准输出,默认输出
  Level:      logger.DebugLevel, // 打印日志级别
  Filename:   "./log.log",    // 日志文件,为空则只输出到标准输出
  MaxSize:    10,             // 日志文件最多写入多大,单位MB
  MaxBackups: 10,             // 保存多少份日志文件
  MaxAge:     20,             // 日志文件保存多长时间,单位天
  Compress:   false,          // 备份的日志文件是否压缩
 }

 // 接收一个配置对象和多个hook
 logger.InitLogger(&opt, logInfoHook)

 logger.Debug("debug")
 logger.Infof("current time %s", time.Now().Format("20060102"))
 // 输出不带任何附加信息的日志
 logger.Pure("11", 22, "33")
}

// 可以定义多个hook,在打印日志的时候做自定义操作,例如异步推送到ES数据等
func logInfoHook(info logger.LogInfo) error {
 fmt.Printf("正在打印日志:%#v\n", info)
 return nil
}

关于Pure方法

有时候我们可能需要输出纯粹的内容,而不是被日志组件格式化的内容,因为调用日志组件的打印方法会在我们的日志内容中追加时间、打印日志的代码位置等信息。但是有些时候我们希望只输出我们的日志内容即可,不需要追加额外的信息。

例如将gorm的日志打印进我们的logger日志系统中,因为gorm的日志会带有时间和调用代码的位置信息,如果调用logger其他打印日志方法可能会因为追加信息太多而造成混乱,所以这种情况就可以调用Pure或者Puref方法去打印原始的日志内容:

func InitDb() {
 if db, err := gorm.Open(config.DatabaseConf.DbName, config.DatabaseConf.DbSource); err != nil {
  logger.Errorf("初始化数据库发生错误:%v", err)
 }
 if config.DatabaseConf.EnvModel {
  db.LogMode(true)
 } else {
  db.LogMode(false)
 }
 db.SetLogger(gormLogger{})
 db.DB().SetConnMaxLifetime(time.Second * time.Duration(config.DatabaseConf.ConnMaxLifetime))
 db.DB().SetMaxIdleConns(config.DatabaseConf.MaxIdleConns)
 db.DB().SetMaxOpenConns(config.DatabaseConf.MaxOpenConns)
}

type gormLogger struct{}

func (gormLogger) Print(values ...interface{}) {
 logger.Pure(gorm.LogFormatter(values...)...)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DPanic

func DPanic(args ...interface{})

DPanic uses fmt.Sprint to construct and log a message. In development, the logger then panics. (See DPanicLevel for details.)

func DPanicf

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

DPanicf uses fmt.Sprintf to log a templated message. In development, the logger then panics. (See DPanicLevel for details.)

func DPanicw

func DPanicw(msg string, keysAndValues ...interface{})

DPanicw logs a message with some additional context. In development, the logger then panics. (See DPanicLevel for details.) The variadic key-value pairs are treated as they are in With.

func Debug

func Debug(args ...interface{})

Debug uses fmt.Sprint to construct and log a message.

func Debugf

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

Debugf uses fmt.Sprintf to log a templated message.

func Debugw

func Debugw(msg string, keysAndValues ...interface{})

Debugw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

When debug-level logging is disabled, this is much faster than

s.With(keysAndValues).Debug(msg)

func Error

func Error(args ...interface{})

Error uses fmt.Sprint to construct and log a message.

func Errorf

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

Errorf uses fmt.Sprintf to log a templated message.

func Errorw

func Errorw(msg string, keysAndValues ...interface{})

Errorw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func Fatal

func Fatal(args ...interface{})

Fatal uses fmt.Sprint to construct and log a message, then calls os.Exit.

func Fatalf

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

Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit.

func Fatalw

func Fatalw(msg string, keysAndValues ...interface{})

Fatalw logs a message with some additional context, then calls os.Exit. The variadic key-value pairs are treated as they are in With.

func GetLogWriter added in v0.0.2

func GetLogWriter() (io.Writer, error)

GetLogWriter 返回一个日志writer,可自定义处理

func Info

func Info(args ...interface{})

Info uses fmt.Sprint to construct and log a message.

func Infof

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

Infof uses fmt.Sprintf to log a templated message.

func Infow

func Infow(msg string, keysAndValues ...interface{})

Infow logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func InitLogger

func InitLogger(opt *Options, hooks ...func(LogInfo) error)

func Panic

func Panic(args ...interface{})

Panic uses fmt.Sprint to construct and log a message, then panics.

func Panicf

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

Panicf uses fmt.Sprintf to log a templated message, then panics.

func Panicw

func Panicw(msg string, keysAndValues ...interface{})

Panicw logs a message with some additional context, then panics. The variadic key-value pairs are treated as they are in With.

func Pure

func Pure(args ...interface{})

Pure Output pure content without any additional information

func Puref

func Puref(msg string, args ...interface{})

Puref Output purely formatted content without any additional information

func Warn

func Warn(args ...interface{})

Warn uses fmt.Sprint to construct and log a message.

func Warnf

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

Warnf uses fmt.Sprintf to log a templated message.

func Warnw

func Warnw(msg string, keysAndValues ...interface{})

Warnw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

Types

type Level

type Level int8

A Level is a logging priority. Higher levels are more important.

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

type LogInfo

type LogInfo struct {
	Level      Level     // 日志级别
	Time       time.Time // 写日志的时间
	LoggerName string    // 写日志组件的名称
	Message    string    // 日志内容
	Stack      string    // 日志堆栈信息
	File       string    // 写日志操作的代码文件
	Line       int       // 写日志操作的代码行数
}

LogInfo 正在写入的日志信息

type Options

type Options struct {
	NotStdout  bool // 不写标准输出吗?默认输出到标准输出,不管有无写文件
	Level      Level
	Filename   string        // 文件为空时,只输出到标准输出
	MaxSize    int64         // megabytes
	MaxBackups int           // MaxBackups is the maximum number of old log files to retain
	MaxAge     time.Duration // MaxAge is the maximum number of days to retain old log files based on the timestamp encoded in their filename
	Compress   bool
}

func GetDefault

func GetDefault(filename string) *Options

GetDefault 获取除文件名外的默认配置:日志文件最大100M,备份最多10个,最多保存30天的数据,不压缩

Jump to

Keyboard shortcuts

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