You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang实现可跨文件与包复用的自定义日志组件

How to Build a Reusable Logging Component with Logrus for Your CLI Tool

Hey there! I’ve totally been in your shoes—having to copy-paste logging code across multiple packages in a CLI tool is such a drag. The good news is Logrus absolutely supports custom implementations, and it’s actually perfect for building a reusable logging component. Let me walk you through how to set this up:

Step 1: Create a Centralized Logger Package

The key is to wrap Logrus in your own dedicated logger package, so all other parts of your app can import and use it without repeating configuration.

Here’s a quick example of what this package might look like:

package logger

import (
  "github.com/sirupsen/logrus"
  "os"
)

// Initialize a global Logrus instance (configured once)
var log *logrus.Logger

// Init sets up your logging configuration once at app startup
func Init(logLevel string) error {
  log = logrus.New()

  // Customize the log format (text, JSON, or your own custom formatter)
  log.SetFormatter(&logrus.TextFormatter{
    FullTimestamp: true,
    PadLevelText:  true,
  })

  // Set output destination (stdout, file, or even multiple outputs)
  log.SetOutput(os.Stdout)

  // Parse and set the log level (e.g., "debug", "info", "error")
  level, err := logrus.ParseLevel(logLevel)
  if err != nil {
    return err
  }
  log.SetLevel(level)

  return nil
}

// Info logs an info-level message, with optional fields
func Info(message string, fields ...logrus.Fields) {
  if len(fields) > 0 {
    log.WithFields(fields[0]).Info(message)
  } else {
    log.Info(message)
  }
}

// Error logs an error-level message with an attached error and optional fields
func Error(message string, err error, fields ...logrus.Fields) {
  logEntry := log.WithError(err)
  if len(fields) > 0 {
    logEntry = logEntry.WithFields(fields[0])
  }
  logEntry.Error(message)
}

// Add more methods (Debug, Warn, Fatal) as needed for your use case

Step 2: Use the Logger Across Your App

In your main function, initialize the logger once:

package main

import "your-project-path/logger"

func main() {
  // Initialize logger with your desired level (e.g., "info")
  if err := logger.Init("info"); err != nil {
    panic(err)
  }

  // Now use it anywhere else in your app
  logger.Info("CLI tool started", logger.Fields{"version": "1.0.0"})
}

In any other package, just import the logger package and call its methods directly—no more duplicate Logrus setup code!

Step 3: Customize Logrus Further (If Needed)

Logrus is super flexible for customizations beyond basic setup:

  • Custom Hooks: Implement the logrus.Hook interface to send logs to external services (like Slack, ELK, or a database). Just add your hook to the log.Hooks collection in your Init function.
  • Custom Formatters: If the built-in text/JSON formatters don’t fit your needs, write your own by implementing the logrus.Formatter interface. This lets you control every part of the log output string.
  • Custom Outputs: Use io.MultiWriter to send logs to multiple destinations (e.g., stdout and a log file) at the same time. You can even create a custom writer for rotating log files or other specialized behavior.

Alternative: If You Don’t Want Logrus

If Logrus feels overkill, you could wrap Go’s standard library log package in a similar way. But Logrus’s structured logging support and extensibility make it way better for most CLI tools that need more than just basic print statements.

At the end of the day, building a reusable logging component with Logrus is totally doable—it’s all about centralizing the configuration and exposing clean, consistent methods for your app to use.

内容的提问来源于stack exchange,提问作者user6124024

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:26:04