Wrap zap for easy using.

go-project-pkg/log

Wrap zap for easy using.

Installation

$ go get -u github.com/go-project-pkg/log

Usage

Use default logger:

import "github.com/go-project-pkg/log"

func main() {
    defer log.Sync()

    log.Info("Hello world!")
    log.Info("Hello ", log.String("string_key", "value"), log.Int("int_key", 666))
    log.Infof("Hello %s!", "world")
    log.Infow("Hello ", "string_key", "value", "int_key", 666)

    log.WithName("logger1").Warn("I am logger1")
    log.WithName("logger2").Warn("I am logger2")

    log.WithFields(log.String("f1", "value"), log.Int("f2", 888)).Error("Hello world!")
    log.WithName("logger3").WithFields(log.String("f1", "value"), log.Int("f2", 888)).Error("Hello world!")

    ctx := log.WithFields(String("f1", "value"), Int("f2", 888)).ToContext(context.Background())
    log.FromContext(ctx).Info("hello world!")
}

Custom your own logger:

import "github.com/go-project-pkg/log"

func init() {
    opts := &log.Options{
        Name:              "",        // logger name
        Level:             "debug",   // debug, info, warn, error, panic, dpanic, fatal
        Format:            "console", // json, console/text
        DisableColor:      false,
        DisableCaller:     false,
        DisableStacktrace: false,
        // Aplication's all levels logs.
        OutputPaths: []string{
            "stdout", // os.Stdout
            "/var/log/app/app.log",
        },
        // Only include zap internal errors, not include application's any level logs.
        ErrorOutputPaths: []string{
            "stderr", // os.Stderr
            "/var/log/app/error.log",
        },
        // Enable log files rotation feature or not.
        EnableRotate: true,
        // Take effect when EnableRotate is true.
        RotateOptions: &log.RotateOptions{
            // Maximum size in megabytes of the log file before it gets rotated.
            // Default: 100, if the value is 0, the log files will not be rotated.
            MaxSize:    1,
            // Saved days, default 0, means no limit.
            MaxAge:     30,
            // Saved count, default 0, means no limit.
            MaxBackups: 2,
            // Use local time in log file name, default false.
            LocalTime:  true,
            // Gzip log files, default false.
            Compress:   false,
        },
    }

    log.Init(opts)
}

func main() {
    defer log.Sync()

    log.Info("Hello world!")
    log.Info("Hello ", log.String("string_key", "value"), log.Int("int_key", 666))
    log.Infof("Hello %s!", "world")
    log.Infow("Hello ", "string_key", "value", "int_key", 666)

    log.WithName("logger1").Warn("I am logger1")
    log.WithName("logger2").Warn("I am logger2")

    log.WithFields(log.String("f1", "value"), log.Int("f2", 888)).Error("Hello world!")
    log.WithName("logger3").WithFields(log.String("f1", "value"), log.Int("f2", 888)).Error("Hello world!")

    ctx := log.WithFields(String("f1", "value"), Int("f2", 888)).ToContext(context.Background())
    log.FromContext(ctx).Info("hello world!")

    // log files rotation test
    for i := 0; i <= 20000; i++ {
        log.Infof("hello world: %d", i)
    }
}

Use log.C(ctx context.Context) for getting logger with additional log fields by cooperating with gin's middleware:

import "github.com/go-project-pkg/log"

// A middleware of gin for setting logger that with custom fileds to gin.Context
func Context() gin.HandlerFunc {
    return func(c *gin.Context) {
        l := log.WithFields(
            log.String("x-request-id", c.GetString(XRequestIDKey)),
            log.String("username", c.GetString(UsernameKey)),
        )
        c.Set(log.ContextLoggerName, l)

        c.Next()
    }
}

// Others place that use the logger.
func (u *UserController) Get(c *gin.Context) {
    // Get logger that with fileds from gin.Context and log a message.
    log.C(c).Debug("user get called")
}

You can add hooks to realize some useful features, like alerting when encountering error logs.

Use log.SetHooks(hooks ...log.Hook) for global logger:

= log.ErrorLevel { fmt.Println("hook2 alert! log entry: %v", entry) } return nil } log.SetHooks(monitorHook1, monitorHook2) log.Error("set hooks: server error") } ">
func main() {
    defer log.Sync()

    monitorHook1 := func(entry log.Entry) error {
        if entry.Level >= log.ErrorLevel {
            fmt.Printf("hook1 alert! log entry: %v", entry)
        }

        // This error is zap internal error, and it will write to 'ErrorOutputPaths'.
        return errors.New("alert hook failed")
    }

    monitorHook2 := func(entry log.Entry) error {
        if entry.Level >= log.ErrorLevel {
            fmt.Println("hook2 alert! log entry: %v", entry)
        }

        return nil
    }

    log.SetHooks(monitorHook1, monitorHook2)

    log.Error("set hooks: server error")
}

Use log.WithHooks(hooks ...log.Hook) for current logger instance:

func main() {
    defer log.Sync()

    monitorHook1 := func(entry log.Entry) error {
        if entry.Level >= log.ErrorLevel {
            fmt.Println("hook1 alert! log entry: %v", entry)
        }

        // This error is zap internal error, and it will write to 'ErrorOutputPaths'.
        return errors.New("alert hook failed")
    }

    log.WithHooks(monitorHook1).Error("with hooks: server error")
}

License

This project is under the MIT License. See the LICENSE file for the full license text.

Similar Resources

A fast and easy-to-use gutenberg book downloader

Gutenberg Downloader A brief description of what this project does and who it's for Usage download books Download all english books as epubs with imag

Jan 11, 2022

Parse a shell script and output all export declarations in an easy to read format

Find Exports Parse a shell script and output all export declarations in an easy to read format. Usage Example $ findexports ~/.bashrc PATH=$PATH:/usr/

Jan 13, 2022

HyperKit: an easy-to-use bridge between LedFX, WLED, Bluetooth, HomeKit, and AirPlay2

HyperKit HyperKit is an easy-to-use bridge between LedFX, WLED, Bluetooth, HomeKit, and AirPlay2. HyperKit Functionality: Custom HomeKit Menu Integrat

Aug 20, 2022

[Building]Use Go & Vue3 to build an easy blog

Go + Vue3 Study 环境安装 本地环境:Go 1.17 后端框架:Gin 注意Go在使用Go Module的话需要使用修改Go的代理 首先查看Go相关的环境变量 go env 修改Go代理 go env -w Go111MODULE=on go env -w GOPROXY=https:

Jan 25, 2022

A easy-to-use and lightweight Go RPC framwork

zrpc 一个简单易用的Go RPC框架 功能 负载均衡(一致性哈希,Round-Robin, 随机) 服务注册与发现 心跳功能 超时处理(调用超时,连接超时,处理超时) 支持TCP/HTTP网络协议 连接复用 同步/异步调用 支持gob/json序列化协议 简单用法 创建注册中心 l, _ :=

Oct 30, 2022

Linux UDisks2 (dbus) easy access from Go

udisks udisks gives you high level access to Linux system drives and block devices wrapping the udisk2 interfaces. An example command line udisks clie

Apr 25, 2022

A distributed unique ID generator of using Sonyflake and encoded by Base58

Indigo About A distributed unique ID generator of using Sonyflake and encoded by Base58. ID max length is 11 characters by unsigned int64 max value. A

Nov 24, 2022

Visualize call graph of a Go program using Graphviz

Visualize call graph of a Go program using Graphviz

go-callvis go-callvis is a development tool to help visualize call graph of a Go program using interactive view. Introduction The purpose of this tool

Dec 31, 2022

generate my_github status using GitHub Actions

generate my_github status using GitHub Actions

generate my_github status using GitHub Actions

Sep 21, 2022
:sunglasses:Package captcha provides an easy to use, unopinionated API for captcha generation

Package captcha provides an easy to use, unopinionated API for captcha generation. Why another captcha generator? I want a simple and framework-indepe

Dec 28, 2022
An easy to use, extensible health check library for Go applications.

Try browsing the code on Sourcegraph! Go Health Check An easy to use, extensible health check library for Go applications. Table of Contents Example M

Dec 30, 2022
safe and easy casting from one type to another in Go

cast Easy and safe casting from one type to another in Go Don’t Panic! ... Cast What is Cast? Cast is a library to convert between different go types

Jan 7, 2023
Easy environment variables for Go

env Easy environment variables for Go Usage import "github.com/darkhelmet/env" ... s := env.String("USER") // Will panic if USER is not present sd :

Dec 21, 2018
Yubigo is a Yubikey client API library that provides an easy way to integrate the Yubico Yubikey into your existing Go-based user authentication infrastructure.

yubigo Yubigo is a Yubikey client API library that provides an easy way to integrate the Yubikey into any Go application. Installation Installation is

Oct 27, 2022
IBus Engine for GoVarnam. An easy way to type Indian languages on GNU/Linux systems.

IBus Engine For GoVarnam An easy way to type Indian languages on GNU/Linux systems. goibus - golang implementation of libibus Thanks to sarim and haun

Feb 10, 2022
An easy-to-use Map Reduce Go parallel-computing framework inspired by 2021 6.824 lab1. It supports multiple workers on a single machine right now.

MapReduce This is an easy-to-use Map Reduce Go framework inspired by 2021 6.824 lab1. Feature Multiple workers on single machine right now. Easy to pa

Dec 5, 2022
General releases made easy for golang

release General releases made easy What it is Release is inspired to GoReleaser for automates general releases that, in most cases, does not require a

Jan 7, 2022
Hrple is an easy to use tool to help you create habits
Hrple is an easy to use tool to help you create habits

Hrple is an easy to use tool to help you create habits. This is loosely inspired by the book Atomic Habits by James Clear and techniques or frameworks like Kanban and the Pomodoro Technique.

Jun 2, 2022
Eye - An easy-use lib for event-driven pattern

?? Eye Eye 是一个简单易用的事件驱动模式库。 Read me in English ?? 功能特性 敬请期待。。。 历史版本的特性请查看 HISTOR

Jan 17, 2022