"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > GoFrame logging from entry to mastery: zero-basis advancement

GoFrame logging from entry to mastery: zero-basis advancement

Posted on 2025-04-13
Browse:203

Mastering GoFrame Logging: From Zero to Hero

GoFrame Efficient Logging System Guide: From Beginner to Mastery

]

summary

GoFrame provides a powerful, easy to configure and highly flexible logging system. This guide covers everything from basic logging to advanced features such as log rotation, custom formatting, and log sharding, and is ideal for Go developers who want to achieve robust logging in their applications!

Why pay attention to the GoFrame log system?

Have you ever struggled with messy logs or spent hours debugging because you couldn't find the correct log entry? GoFrame's log module will help you! Whether you are building small services or large applications, proper logging is crucial. Let's dive into how GoFrame makes logging powerful and easy.

This guide covers:

  • Basic log settings and usage
  • Log level and its importance
  • Log rotation (because no one likes huge log files!)
  • Custom formatting for better readability
  • Advanced technologies such as log sharding
  • Practical examples you can use immediately

Basic settings

]

Let's start with the basics. GoFrame's log module (glog) provides several easy-to-use functions you will like:

import "github.com/gogf/gf/v2/os/glog"

func main() {
    // 简单日志记录
    glog.Debug("调试信息")  // 用于开发人员
    glog.Info("信息")    // 一般信息
    glog.Warn("警告!")        // 注意!
    glog.Error("错误!")         // 出现问题
    glog.Fatal("严重错误!")     // 出现严重问题
}

? Professional tips: Start at the Info level in a production environment and use the Debug level in a development environment. You will thank me in the future!

Intelligent log file management

]

One of my favorite features is automatic log rotation. No need to clean files manually! Here is the setup method:

import "github.com/gogf/gf/v2/os/glog"

func main() {
    l := glog.New()
    l.SetPath("./logs")                    // 日志存储位置
    l.SetFile("app-{Ymd}.log")            // 每日轮转!

    // 您的日志现在将按日期组织
    l.Info("这将写入今天的日志文件")
}

{Ymd} mode in the filename means that you will get the following file:

  • app-20241124.log
  • app-20241125.log
  • etc...

Log level: Select your level of detail

Treat the log level as the volume knob for the log. Here are the ways to use them effectively:

import "github.com/gogf/gf/v2/os/glog"

func main() {
    ctx := gctx.New()
    l := glog.New()

    // 只显示警告及以上级别
    l.SetLevel(glog.LEVEL_WARN)

    // 这些不会显示
    l.Debug(ctx, "调试信息...")
    l.Info(ctx, "仅供参考...")

    // 这些将显示
    l.Warning(ctx, "注意!")
    l.Error(ctx, "休斯顿,我们有问题!")
}

Beautify your log

]

No one likes ugly logs! Here's how to make them easier to read:

import "github.com/gogf/gf/v2/os/glog"

func main() {
    ctx := gctx.New()
    l := glog.New()

    // 添加时间戳和文件信息
    l.SetFlags(glog.F_TIME_STD | glog.F_FILE_SHORT)

    // 添加自定义字段
    l.Infof(ctx, "用户 %d 从 %s 登录", 12345, "192.168.1.1")
}

Output:

2024-11-24 14:30:00 [INFO] main.go:12: 用户 12345 从 192.168.1.1 登录

Advanced: Log sharding

Entering in large-scale projects? You may want to split the logs based on the log type. Here is a clever way:

import "github.com/gogf/gf/v2/os/glog"

func main() {
    ctx := gctx.New()

    // 创建单独的日志记录器
    access := glog.New()
    errors := glog.New()

    // 以不同的方式配置它们
    access.SetFile("access-{Ymd}.log")
    errors.SetFile("errors-{Ymd}.log")

    // 在适当的地方使用它们
    access.Info(ctx, "用户查看了主页")
    errors.Error(ctx, "无法连接到数据库")
}

Custom format to meet special needs

]

Do you need to format the logs in a specific way? Maybe it's for log aggregation tool? Here is the method:

import (
    "fmt"
    "github.com/gogf/gf/v2/os/glog"
    "time"
)

type CustomWriter struct{}

func (w *CustomWriter) Write(p []byte) (n int, err error) {
    // 添加 JSON 格式
    log := fmt.Sprintf(`{"time":"%s","message":"%s"}`, 
        time.Now().Format(time.RFC3339),
        string(p))
    fmt.Print(log)
    return len(log), nil
}

func main() {
    l := glog.New()
    l.SetWriter(&CustomWriter{})
    l.Print("发生了一些事情!")
}

Quick success prompt

]
  1. Start small: Start with basic logging and add complexity as needed
  2. Use log levels wisely : Debugging is used for development, information is used for general operations, errors are used for problems
  3. Rotate your logs: Set up log rotation from day one - your disk space will thank you
  4. Add context: Include relevant user information, such as user ID, request ID, etc.
  5. Monitor log size: Use SetFile with date mode to manage log growth

Summarize

Log logging may not be the most exciting part of development, but it is definitely one of the most important parts. With GoFrame's logging module, you can use all the necessary tools to implement a powerful logging system, which will make your life easier when something goes wrong (and always happens!).

Next step?

  • Try to implement these examples in your project
  • Try different log formats
  • Set log rotation according to your needs
  • Consider adding structured logs for better analysis

I wish you a happy logging! ?


Cover photo is from XYZ

on Unsplash

Discussion issues

How do you handle logging in a Go project? What challenges do you face and how does GoFrame's logging module help solve these challenges? Please let me know in the comments! ?

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3