Logging

Logging #

We can use logs to observe program behavior, diagnose problems, or configure corresponding alarms. And defining a well structured log can improve search efficiency and facilitate handling of problems.

gFly provides a default way to print logs in the standard output. It also provides several global functions, such as log.Info, log.Errorf, log.Warnw, etc. Log content can also be written to a file storage/logs/logs.log

You can change log setting in .env at log section

# NOTE: Log settings:
#   - Trace|Debug|Info|Warn|Error|Fatal|Panic
LOG_CHANNEL=file
LOG_FILE=logs.log
LOG_LEVEL=Trace

Log levels #

const (
    LevelTrace Level = iota
    LevelDebug
    LevelInfo
    LevelWarn
    LevelError
    LevelFatal
    LevelPanic
)

Note: The method of calling the Fatal level will interrupt the program running after printing the log, please use it with caution. Directly print logs of different levels, which will be entered into messageKey, the default is msg.

log.Info("Hello, World!")
log.Debug("Are you OK?")
log.Info("42 is the answer to life, the universe, and everything")
log.Warn("We are under attack!")
log.Error("Houston, we have a problem.")
log.Fatal("So Long, and Thanks for All the Fislog.")
log.Panic("The system is down.")

Format and print logs of different levels, all methods end with f

log.Debugf("Hello %s", "boy")
log.Infof("%d is the answer to life, the universe, and everything", 233)
log.Warnf("We are under attack %s!", "boss")
log.Errorf("%s, we have a problem.", "Master Shifu")
log.Fatalf("So Long, and Thanks for All the %s.", "banana")

Print a message with the key and value, or KEYVALS UNPAIRED if the key and value are not a pair.

log.Debugw("", "Hello", "boy")
log.Infow("", "number", 233)
log.Warnw("", "job", "boss")
log.Errorw("", "name", "Master Shifu")
log.Fatalw("", "fruit", "banana")

Global log #

If you are in a project and just want to use a simple log function that can be printed at any time in the global, we provide a global log.

import "app/core/log"

log.Info("info")
log.Warn("warn")

The above is using the default log.DefaultLogger standard output. You can also find an already implemented adaptation under contrib, or use your own implemented Logger and use log.SetLogger to set the global log logger.

import (
    "log"
    gflylog "app/core/log"
)

var _ log.AllLogger = (*customLogger)(nil)

type customLogger struct {
    stdlog *log.Logger
}

// ...
// inject your custom logger
gflylog.SetLogger(customLogger)

Set Level #

log.SetLevel sets the level of logs below which logs will not be output. The default logger is LevelTrace.

Note that this method is not concurrent-safe.

import "app/core/log"

log.SetLevel(log.LevelInfo)

Bind context #

Set the context, using the following method will return a CommonLogger instance bound to the specified context

commonLogger := log.WithContext(ctx)
commonLogger.Info("info")
INFO
gFly uses gofiber’s library