logger

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 18 Imported by: 0

README

golang logger

基于uber zap封装而成的logger模块,可用于go应用中记录操作日志和错误日志sentry上报。功能特性如下:

  • 支持日志自动切割和最大保留时长
  • 支持日志json格式化处理
  • 支持日志同时输出到文件和终端
  • 支持日志打印级别和日志染色功能
  • 支持自定义 zap core 注入,例如:sentry错误上报、openobserve日志平台上报,目前已内置sentry错误上报功能

logger output and sentry report

package main

import (
	"context"
	"log"
	"os"
	"time"

	"github.com/getsentry/sentry-go"
	"go.uber.org/zap"

	"github.com/daheige/logger"
)

func main() {
	err := sentry.Init(sentry.ClientOptions{
		Dsn: os.Getenv("SENTRY_DSN"),
	})
	if err != nil {
		log.Fatalf("sentry.Init: %v", err)
	}

	defer sentry.Flush(2 * time.Second)
	// mock sentry report capture message
	// sentry.CaptureMessage("It works!")

	logger.Default(
		logger.WithJsonFormat(true),        // 默认json格式化输出
		logger.WithCallerSkip(2),           // 如果基于这个Logger包,需要设置适当的skip
		logger.WithLogLevel(zap.InfoLevel), // 设置日志打印最低级别,如果不设置,默认为info级别
		logger.WithStdout(true),            // 日志默认输出到终端

		logger.WithEnableSentry(true),          // 开启sentry上报
		logger.WithSentryLevel(zap.ErrorLevel), // 只允许错误级别以上的日志上报
	)

	logger.Info(context.Background(), "hello world", "plat", "mac")
	logger.Error(context.Background(), "exec begin", "foo", "abc")
	logger.DPanic(context.Background(), "exec dpanic", "foo", "abc")
	logger.Error(context.Background(), "auth error", "uid", 1)
}

sentry上报效果如下: sentry.png

zap

https://github.com/uber-go/zap

sentry

https://sentry.io

Documentation

Overview

Package logger for log interface

Package logger 基于zap日志库,进行封装的logger库 支持日志自动切割

Index

Constants

This section is empty.

Variables

View Source
var (
	// XRequestID request_id
	XRequestID = CtxKey{"x-request-id"}

	// ReqClientIP  client_ip
	ReqClientIP = CtxKey{"client_ip"}

	// RequestMethod request method
	RequestMethod = CtxKey{"request_method"}

	// RequestURI request uri
	RequestURI = CtxKey{"request_uri"}

	// UserAgent request ua
	UserAgent = CtxKey{"request_ua"}

	// TimeLocal time local
	TimeLocal = CtxKey{"time_local"}

	// CurHostname current hostname
	CurHostname = CtxKey{"hostname"}

	// Fullstack full stack
	Fullstack = CtxKey{"full_stack"}
)

Functions

func DPanic added in v1.1.0

func DPanic(ctx context.Context, msg string, fields ...interface{})

DPanic 调试模式下的panic,程序不退出,继续运行

func Debug added in v1.1.0

func Debug(ctx context.Context, msg string, fields ...interface{})

Debug debug级别日志

func Default added in v1.1.0

func Default(opts ...Option)

Default 初始化默认zap logger接口 默认日志写到终端中

func Error added in v1.1.0

func Error(ctx context.Context, msg string, fields ...interface{})

Error 错误类型的日志

func Fatal added in v1.1.0

func Fatal(ctx context.Context, msg string, fields ...interface{})

Fatal 抛出致命错误,然后退出程序

func FieldToValue added in v1.2.0

func FieldToValue(f zap.Field) interface{}

FieldToValue 将zap field类型转换为 interface

func Info added in v1.1.0

func Info(ctx context.Context, msg string, fields ...interface{})

Info info级别日志

func MaskAllString added in v1.2.0

func MaskAllString(s string) string

MaskAllString 全部打码

func MaskString added in v1.2.0

func MaskString(s string) string

MaskString 对字符串进行打码:保留前3位和后4位,中间替换为* 适用于长度在 7 位及以上的字符串(涵盖8-12位场景)

func Md5

func Md5(str string) string

Md5 md5 func

func NewLogSugar

func NewLogSugar(opts ...Option) *zap.SugaredLogger

NewLogSugar zap log sugar语法糖 支持Debug,Info,Error,Panic,Warn,Fatal等方法 返回一个*zap.SugaredLogger

func Panic added in v1.1.0

func Panic(ctx context.Context, msg string, fields ...interface{})

Panic 抛出panic的时候,先记录日志,然后执行panic,退出当前goroutine 如果没有捕获,就会退出当前程序,建议程序做defer捕获处理

func RandInt64

func RandInt64(min, max int64) int64

RandInt64 get a num in [m,n]

func Recover added in v1.1.0

func Recover(ctx context.Context, msg string, fields ...interface{})

Recover 用来捕获程序运行出现的panic信息,并记录到日志中 这个panic信息,将采用 DPanic 方法进行记录

func RndUUID

func RndUUID() string

RndUUID realizes unique uuid based on time ns and random number There is no duplication of uuid on a single machine If you want to generate non-duplicate uuid on a distributed architecture Just add some custom strings in front of rndStr Return format: eba1e8cd0460491049c644bdf3cf024d

func RndUUIDMd5

func RndUUIDMd5() string

RndUUIDMd5 make an md5 uuid

func Uuid added in v1.1.0

func Uuid() string

Uuid 生成 version4 的uuid 返回格式:eba1e8cd0460491049c644bdf3cf024d

func Warn added in v1.1.0

func Warn(ctx context.Context, msg string, fields ...interface{})

Warn 警告类型的日志

Types

type CtxKey

type CtxKey struct {
	Name string
}

CtxKey ctx key struct.

func (CtxKey) String

func (c CtxKey) String() string

String CtxKey string.

type Logger

type Logger interface {
	// Debug debug级别日志
	Debug(ctx context.Context, msg string, fields ...interface{})

	// Info info级别日志
	Info(ctx context.Context, msg string, fields ...interface{})

	// Error 错误类型的日志
	Error(ctx context.Context, msg string, fields ...interface{})

	// Warn 警告类型的日志
	Warn(ctx context.Context, msg string, fields ...interface{})

	// DPanic 调试模式下的panic,程序不退出,继续运行
	DPanic(ctx context.Context, msg string, fields ...interface{})

	// Recover 用来捕获程序运行出现的panic信息,并记录到日志中
	// 这个panic信息,将采用 DPanic 方法进行记录
	Recover(ctx context.Context, msg string, fields ...interface{})

	// Panic 抛出panic的时候,先记录日志,然后执行panic,退出当前goroutine
	// 如果没有捕获,就会退出当前程序,建议程序做defer捕获处理
	Panic(ctx context.Context, msg string, fields ...interface{})

	// Fatal 抛出致命错误,然后退出程序
	Fatal(ctx context.Context, msg string, fields ...interface{})
}

Logger interface.

func New

func New(opts ...Option) Logger

New 创建一个Logger interface.

type Option

type Option func(z *zapLogWriter)

Option option for zapLogWriter

func WithAddCaller

func WithAddCaller(b bool) Option

WithAddCaller 是否输出文件名和行号

func WithCallerSkip

func WithCallerSkip(skip int) Option

WithCallerSkip 设置 skip addCaller = true,并且 callerSkip > 0 会设置zap.AddCallerSkip zap源码包中logger.go#260 check func check must always be called directly by a method in the Logger interface (e.g., Check, Info, Fatal). const callerSkipOffset = 2 这里的callerSkipOffset默认是2 如果基于这个Logger包,再包装一次,这个 skip = 2,以此类推 否则 skip=1

func WithCompress

func WithCompress(b bool) Option

WithCompress 日志是否压缩

func WithCores added in v1.2.0

func WithCores(cores ...zapcore.Core) Option

WithCores 设置 zap cores

func WithEnableColor

func WithEnableColor(b bool) Option

WithEnableColor 是否日志染色

func WithEnableSentry added in v1.2.0

func WithEnableSentry(b bool) Option

WithEnableSentry 是否开启sentry上报

func WithHostname

func WithHostname(hostname string) Option

WithHostname 自定义hostname

func WithJsonFormat

func WithJsonFormat(b bool) Option

WithJsonFormat 是否json格式化

func WithLogDir

func WithLogDir(dir string) Option

WithLogDir 日志目录

func WithLogFilename

func WithLogFilename(filename string) Option

WithLogFilename 日志文件名

func WithLogLevel

func WithLogLevel(level zapcore.Level) Option

WithLogLevel 日志级别,设置日志打印最低级别,如果不设置默认为info级别 zap.InfoLevel is the default logging priority.

func WithMaxAge

func WithMaxAge(d int) Option

WithMaxAge 日志保留时间,单位day

func WithMaxSize

func WithMaxSize(size int) Option

WithMaxSize 日志大小,单位MB

func WithSentryFlushTimeout added in v1.2.0

func WithSentryFlushTimeout(d time.Duration) Option

WithSentryFlushTimeout 设置 sentry flush timeout

func WithSentryLevel added in v1.2.0

func WithSentryLevel(level zapcore.Level) Option

WithSentryLevel 设置 sentry 上报的 zap level

func WithStdout

func WithStdout(b bool) Option

WithStdout 是否输出到终端

func WithWriteToFile added in v1.2.0

func WithWriteToFile(b bool) Option

WithWriteToFile 设置日志是否写入文件中

Directories

Path Synopsis
sentry command

Jump to

Keyboard shortcuts

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