Logo

dev-resources.site

for different kinds of informations.

Mastering GoFrame Logging: From Zero to Hero

Published at
1/12/2025
Categories
go
logging
goframe
tutorial
Author
jones_charles_ad50858dbc0
Categories
4 categories in total
go
open
logging
open
goframe
open
tutorial
open
Author
25 person written this
jones_charles_ad50858dbc0
open
Mastering GoFrame Logging: From Zero to Hero

Cover image showing logs flowing through a digital interface

TLDR

GoFrame provides a powerful logging system that's easy to set up and highly configurable. This guide covers everything from basic logging to advanced features like log rotation, custom formatting, and log sharding. Perfect for Go developers looking to implement robust logging in their applications!

🌟 Why You Should Care

Ever struggled with messy logs or spent hours debugging because you couldn't find the right log entry? GoFrame's logging module is here to save the day! Whether you're building a small service or a large-scale application, proper logging is crucial. Let's dive into how GoFrame makes logging both powerful and painless.

🎯 What We'll Cover

  • Basic logging setup and usage
  • Log levels and why they matter
  • Log rotation (because nobody likes huge log files!)
  • Custom formatting for better readability
  • Advanced techniques like log sharding
  • Real-world examples you can use today

🔧 Basic Setup

Let's start with the basics. GoFrame's logging module (glog) comes with several easy-to-use methods that you'll love:

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

func main() {
    // Simple logging
    glog.Debug("Debug message")  // For developers
    glog.Info("Info message")    // General information
    glog.Warn("Warning!")        // Heads up!
    glog.Error("Oops!")         // Something's wrong
    glog.Fatal("Critical!")     // Time to panic
}
Enter fullscreen mode Exit fullscreen mode

💡 Pro tip: Start with Info level in production and Debug in development. You can thank me later!

📁 Smart Log File Management

One of my favorite features is automatic log rotation. No more manual file cleanup! Here's how to set it up:

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

func main() {
    l := glog.New()
    l.SetPath("./logs")                    // Where to store logs
    l.SetFile("app-{Ymd}.log")            // Daily rotation!

    // Your logs will now be organized by date
    l.Info("This goes to today's log file")
}
Enter fullscreen mode Exit fullscreen mode

The {Ymd} pattern in the filename means you'll get files like:

  • app-20241124.log
  • app-20241125.log
  • And so on...

🎚️ Log Levels: Choose Your Verbosity

Think of log levels like a volume knob for your logs. Here's how to use them effectively:

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

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

    // Only show warnings and above
    l.SetLevel(glog.LEVEL_WARN)

    // These won't show up
    l.Debug(ctx, "Debugging stuff...")
    l.Info(ctx, "Just FYI...")

    // These will show up
    l.Warning(ctx, "Watch out!")
    l.Error(ctx, "Houston, we have a problem!")
}
Enter fullscreen mode Exit fullscreen mode

💅 Making Your Logs Pretty

Nobody likes ugly logs! Here's how to make them more readable:

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

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

    // Add timestamps and file info
    l.SetFlags(glog.F_TIME_STD | glog.F_FILE_SHORT)

    // Add custom fields
    l.Infof(ctx, "User %d logged in from %s", 12345, "192.168.1.1")
}
Enter fullscreen mode Exit fullscreen mode

Output:

2024-11-24 14:30:00 [INFO] main.go:12: User 12345 logged in from 192.168.1.1
Enter fullscreen mode Exit fullscreen mode

🔄 Advanced: Log Sharding

Working on a bigger project? You might want to split your logs based on their type. Here's a cool way to do it:

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

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

    // Create separate loggers
    access := glog.New()
    errors := glog.New()

    // Configure them differently
    access.SetFile("access-{Ymd}.log")
    errors.SetFile("errors-{Ymd}.log")

    // Use them where appropriate
    access.Info(ctx, "User viewed homepage")
    errors.Error(ctx, "Failed to connect to database")
}
Enter fullscreen mode Exit fullscreen mode

🎨 Custom Formatting for Special Needs

Need to format logs in a specific way? Maybe for log aggregation tools? Here's how:

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

type CustomWriter struct{}

func (w *CustomWriter) Write(p []byte) (n int, err error) {
    // Add JSON formatting
    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("Something happened!")
}
Enter fullscreen mode Exit fullscreen mode

🚀 Quick Tips for Success

  1. Start Simple: Begin with basic logging and add complexity as needed
  2. Use Log Levels Wisely: Debug for development, Info for general operations, Error for problems
  3. Rotate Your Logs: Set up log rotation from day one - your disk space will thank you
  4. Add Context: Include relevant information like user IDs, request IDs, etc.
  5. Monitor Log Size: Use SetFile with date patterns to manage log growth

🎉 Wrapping Up

Logging might not be the most exciting part of development, but it's definitely one of the most important. With GoFrame's logging module, you have all the tools you need to implement a robust logging system that will make your life easier when things go wrong (and they always do!).

🤔 What's Next?

  • Try implementing these examples in your project
  • Experiment with different log formats
  • Set up log rotation based on your needs
  • Consider adding structured logging for better analysis

Happy logging! 🚀


Cover photo by XYZ on Unsplash

Discussion Question

How do you handle logging in your Go projects? What challenges have you faced, and how did GoFrame's logging module help solve them? Let me know in the comments! 👇

Featured ones: