打赏

golang zap日志使用

zap日志使用

package main

import (
	"encoding/json"
	"fmt"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func initLogger (logpath string,loglevel string) *zap.Logger {
	hook := lumberjack.Logger{
		Filename:   logpath,  //日志文件路径
		MaxSize:    128, //最大字节
		MaxAge:     30,
		MaxBackups: 7,
		Compress:   true,
	}
	w := zapcore.AddSync(&hook)
	// 设置日志级别,debug可以打印出info,debug,warn;info级别可以打印warn,info;warn只能打印warn
    // debug->info->warn->error
    var level zapcore.Level
	switch loglevel {
	case "debug":
		level = zap.DebugLevel
	case "info":
		level= zap.InfoLevel
	case "error":
		level = zap.ErrorLevel
	default:
		level = zap.InfoLevel
	}

	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	core := zapcore.NewCore(
		zapcore.NewConsoleEncoder(encoderConfig),
		w,
		level,
	)

	logger := zap.New(core)
	logger.Info("DefaultLogger init success")
	return logger
}

type Person struct {
	Name string `json:"name"`
	Age int `json:"age"`
}

func main(){
	t:= &Person{
		Name: "zhangsan",
		Age:  21,
	}
	data,err := json.Marshal(t)
	if err!=nil {
		fmt.Println("marshal is failed,err:",err)
	}

	// 历史记录日志名字为:all-2018-11-15T07-45-51.763.log,服务重新启动,日志会追加,不会删除
	logger := initLogger("./all.log","debug")
	for i:=0;i<6;i++{
		//结构化日志输出,即字段和消息
		//字段用来结构化输出错误相关的上下文环境,而消息简明扼要的阐述错误本身
		logger.Info(fmt.Sprint("test log",i),zap.Int("line",47))
		logger.Debug(fmt.Sprint("debug log",i),zap.ByteString("level",data))
		logger.Info(fmt.Sprint("Info log",i),zap.String("level",`{"a":"4","b":"5"}`))
		logger.Warn(fmt.Sprint("Info log ", i), zap.String("level", `{"a":"7","b":"8"}`))
		// 用户不存在的错误消息
		logger.Error("User does not exist",zap.String("Name",t.Name))
	}
	//supgar的使用,不推荐,适合简单使用
	sugar := logger.Sugar()
	sugar.Debugf("hello world : %s","zap-sugar")
}

示例代码二

package logger

import (
	"os"
	"time"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	lumberjackv2 "gopkg.in/natefinch/lumberjack.v2"
)

const (
	Console = "console"
	File    = "file"
)

var (
	Leavel = zap.DebugLevel
	Target = Console
)

var (
	Logger *zap.Logger
	Sugar  *zap.SugaredLogger
)

func NewEncoderConfig() zapcore.EncoderConfig {
	return zapcore.EncoderConfig{
		// Keys can be anything except the empty string.
		TimeKey:        "T",
		LevelKey:       "L",
		NameKey:        "N",
		CallerKey:      "C",
		MessageKey:     "M",
		StacktraceKey:  "S",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.CapitalLevelEncoder,
		EncodeTime:     TimeEncoder,
		EncodeDuration: zapcore.StringDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}
}

func TimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
	enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
}

func init() {
	w := zapcore.AddSync(&lumberjackv2.Logger{
		Filename:   "log/im.log",
		MaxSize:    1024, // megabytes
		MaxBackups: 10,
		MaxAge:     7, // days
	})

	var writeSyncer zapcore.WriteSyncer
	if Target == Console {
		writeSyncer = zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout))
	}
	if Target == File {
		writeSyncer = zapcore.NewMultiWriteSyncer(w)
	}

	core := zapcore.NewCore(
		zapcore.NewConsoleEncoder(NewEncoderConfig()),
		writeSyncer,
		Leavel,
	)
	Logger = zap.New(core, zap.AddCaller())
	Sugar = Logger.Sugar()
}

示例代码三

package logger

import (
	"github.com/astaxie/beego"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
)

// 初始化zaplogger日志库
var MyLogger *zap.Logger

func initLogger(logpath string) *zap.Logger {
	hook := lumberjack.Logger{
		Filename:   logpath, // 日志文件路径
		MaxSize:    128,     // 每个日志文件保存的最大尺寸 单位:M
		MaxBackups: 30,      // 日志文件最多保存多少个备份
		MaxAge:     7,       // 文件最多保存多少天
		Compress:   true,    // 是否压缩
	}

	encoderConfig := zapcore.EncoderConfig{
		TimeKey:        "time",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "linenum",
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,  // 小写编码器
		EncodeTime:     zapcore.ISO8601TimeEncoder,     // ISO8601 UTC 时间格式
		EncodeDuration: zapcore.SecondsDurationEncoder, //
		EncodeCaller:   zapcore.ShortCallerEncoder,      // 短路径编码器
		EncodeName:     zapcore.FullNameEncoder,
	}

	// 设置日志级别
	atomicLevel := zap.NewAtomicLevel()
	atomicLevel.SetLevel(zap.DebugLevel)

	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(encoderConfig),                                           // 编码器配置
		zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(&hook)), // 打印到控制台和文件
		atomicLevel,                                                                     // 日志级别
	)

	// 开启开发模式,堆栈跟踪
	caller := zap.AddCaller()
	// 开启文件及行号
	development := zap.Development()

	// 设置初始化字段
	filed := zap.Fields(zap.String("serviceName", "webgo"))
	// 构造日志
	logger := zap.New(core, caller, development, filed)

	logger.Info("log 初始化成功")
	return logger
}

// 初始化日志
func init() {
	logPath := beego.AppConfig.String("LogPath")
	MyLogger = initLogger(logPath)
}
posted @ 2020-04-16 16:52  苍山落暮  阅读(3818)  评论(1编辑  收藏  举报