1 Star 1 Fork 1

menuiis/logx

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
BSD-3-Clause

✒️ logx

logx is a zero-dependency simple, fast and easy-to-use level-based logger written in Go Programming Language.

Output from win terminal

build status report card godocs github issues

🚀 Installation

The only requirement is the Go Programming Language*.

Go modules
$ go get gitee.com/menciis/logx@latest

Or edit your project's go.mod file and execute $ go build.

module your_project_name

go 1.19

require (
    gitee.com/menciis/logx v0.1.8
)

$ go build

$ go get gitee.com/menciis/logx@latest
package main

import (
    "gitee.com/menciis/logx"
)

func main() {
    // Default Output is `os.Stdout`,
    // but you can change it:
    // logx.SetOutput(os.Stderr)

    // Time Format defaults to: "2006/01/02 15:04"
    // you can change it to something else or disable it with:
    // logx.SetTimeFormat("")

    // Level defaults to "info",
    // but you can change it:
    logx.SetLevel("debug")

    logx.Println("This is a raw message, no levels, no colors.")
    logx.Info("This is an info message, with colors (if the output is terminal)")
    logx.Warn("This is a warning message")
    logx.Error("This is an error message")
    logx.Debug("This is a debug message")
    logx.Fatal(`Fatal will exit no matter what,
    but it will also print the log message if logger's Level is >=FatalLevel`)
}

Log Levels

Name Method Text Color
"fatal" Fatal, Fatalf [FTAL] Red background
"error" Error, Errorf [ERRO] Red foreground
"warn" Warn, Warnf, Warningf [WARN] Magenta foreground
"info" Info, Infof [INFO] Cyan foreground
"debug" Debug, Debugf [DBUG] Yellow foreground

On debug level the logger will store stacktrace information to the log instance, which is not printed but can be accessed through a Handler (see below).

Helpers

// GetTextForLevel returns the level's (rich) text. 
fatalRichText := logx.GetTextForLevel(logx.FatalLevel, true)

// fatalRichText == "\x1b[41m[FTAL]\x1b[0m"
// ParseLevel returns a Level based on its string name.
level := logx.ParseLevel("debug")

// level == logx.DebugLevel

Customization

You can customize the log level attributes.

func init() {
    // Levels contains a map of the log levels and their attributes.
    errorAttrs := logx.Levels[logx.ErrorLevel]

    // Change a log level's text.
    customColorCode := 156
    errorAttrs.SetText("custom text", customColorCode)

    // Get (rich) text per log level.
    enableColors := true
    errorRichText := errorAttrs.Text(enableColors)
}

Alternatively, to change a specific text on a known log level, you can just call:

logx.ErrorText("custom text", 156)

Integration

The logx.Logger is using common, expected log methods, therefore you can integrate it with ease.

Take for example the badger database. You want to add a prefix of [badger] in your logs when badger wants to print something.

  1. Create a child logger with a prefix text using the Child function,
  2. disable new lines (because they are managed by badger itself) and you are ready to GO:
opts := badger.DefaultOptions("./data")
opts.Logger = logx.Child("[badger]").DisableNewLine()

db, err := badger.Open(opts)
// [...]

Level-based and standard Loggers

You can put logx in front of your existing loggers using the Install and InstallStd methods.

Any level-based Logger that implements the ExternalLogger can be adapted.

E.g. sirupsen/logrus:

// Simulate a logrus logger preparation.
logrus.SetLevel(logrus.InfoLevel)
logrus.SetFormatter(&logrus.JSONFormatter{})

logx.Install(logrus.StandardLogger())

logx.Debug(`this debug message will not be shown,
    because the logrus level is InfoLevel`)
logx.Error(`this error message will be visible as JSON,
    because of logrus.JSONFormatter`)

Any standard logger (without level capabilities) that implements the StdLogger can be adapted using the InstallStd method.

E.g. log standard package:

// Simulate a log.Logger preparation.
myLogger := log.New(os.Stdout, "", 0)

logx.SetLevel("error")
logx.InstallStd(myLogger)

logx.Error("error message")

Output Format

Any value that completes the Formatter interface can be used to write to the (leveled) output writer. By default the "json" formatter is available.

JSON

import "gitee.com/menciis/logx"

func main() {
    logx.SetLevel("debug")
    logx.SetFormat("json", "    ") // < --

    // main.go#29
    logx.Debugf("This is a %s with data (debug prints the stacktrace too)", "message", logx.Fields{
        "username": "kataras",
    })
}

Output

{
    "timestamp": 1591423477,
    "level": "debug",
    "message": "This is a message with data (debug prints the stacktrace too)",
    "fields": {
        "username": "kataras"
    },
    "stacktrace": [
        {
            "function": "main.main",
            "source": "C:/example/main.go:29"
        }
    ]
}

Register custom Formatter

logx.RegisterFormatter(new(myFormatter))
logx.SetFormat("myformat", options...)

The Formatter interface looks like this:

// Formatter is responsible to print a log to the logger's writer.
type Formatter interface {
	// The name of the formatter.
	String() string
	// Set any options and return a clone,
	// generic. See `Logger.SetFormat`.
	Options(opts ...interface{}) Formatter
	// Writes the "log" to "dest" logger.
	Format(dest io.Writer, log *Log) bool
}

Custom Format using Handler

The Logger can accept functions to handle (and print) each Log through its Handle method. The Handle method accepts a Handler.

type Handler func(value *Log) (handled bool)

This method can be used to alter Log's fields based on custom logic or to change the output destination and its output format.

Create a JSON handler

import "encoding/json"

func jsonOutput(l *logx.Log) bool {
    enc := json.NewEncoder(l.Logger.GetLevelOutput(l.Level.String()))
    enc.SetIndent("", "    ")
    err := enc.Encode(l)
    return err == nil
}

Register the handler and log something

import "gitee.com/menciis/logx"

func main() {
    logx.SetLevel("debug")
    logx.Handle(jsonOutput)

    // main.go#29
    logx.Debugf("This is a %s with data (debug prints the stacktrace too)", "message", logx.Fields{
        "username": "kataras",
    })
}

Examples

🔥 Benchmarks

test times ran (large is better) ns/op (small is better) B/op (small is better) allocs/op (small is better)
BenchmarklogxPrint 10000000 3749 ns/op 890 B/op 28 allocs/op
BenchmarkLogrusPrint   3000000 9609 ns/op 1611 B/op 64 allocs/op

Click here for details.

👥 Contributing

If you find that something is not working as expected please open an issue.

BSD 3-Clause License Copyright (c) 2017-2023, Gerasimos (Makis) Maropoulos (kataras2006@hotmail.com) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

简介

基于 github.com/kataras/golog 展开 收起
Go
BSD-3-Clause
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/menciis/logx.git
git@gitee.com:menciis/logx.git
menciis
logx
logx
master

搜索帮助