SoFunction
Updated on 2025-03-01

Share suggestions on the use of logs in Go language

Standard usage of GO language logs

In any server-side language project, logs are a crucial component. They can record the operating status, error information and critical events of the system, and have an irreplaceable role in problem investigation, performance optimization and system monitoring. Here are some suggestions on how to use GO language logs, as well as actual examples:

1. Log level division: Log levels usually include Debug, Info, Warn, Error, DPanic and Fatal levels. Logs of different levels are used to record information of different degrees of importance.

  • Debug: Used to record detailed debugging information, enabled only during the development and testing phases.
  • Info: Used to record information about normal operation status.
  • Warn: Used to record warnings that some problems may have occurred, but the program still works properly.
  • Error: Used to record error information, indicating that a recoverable error occurred.
  • DPanic: used to log non-fatal errors, but can cause the program to crash.
  • Fatal: used to log fatal errors that will cause the program to terminate.

2. When to print a log of what level: According to the definition of the log level, the corresponding log level should be used in the following situations:

  • Debug: When detailed debugging information is required, such as during the development and testing phases.
  • Info: Record key information and status when the program is running normally.
  • Warn: When you find some possible problems, the program can continue to run.
  • Error: When a recoverable error occurs, it indicates that there is a problem with the program, but it can continue to run.
  • DPanic and Fatal: Usually used to log fatal errors, requiring the program to be stopped immediately.

3. Print format and timestamp: The log format should include time, log level, file name, line number, message and other information. Time zone time is an important consideration to ensure that the time of logging is readable.

4. Log segmentation and storage: The log should switch files in days and set the maximum upper limit of the file to avoid excessive file size. When the daily file size exceeds the threshold, the files for the day need to be numbered in sequence.

5. Practical examples:

Here we use the general log module based on zap encapsulation to centrally process itGeneral modules in Go unified log processing

Web service example:

package main
​
import (
  "/gin-gonic/gin"
  "your_project/common"
)
​
func main() {
  ("Web service started")
​
  router := ()
​
  // Handlers
  ("/", func(c *) {
    ("Handling root endpoint")
    (200, {"message": "Hello, World!"})
  })
​
  // ...
​
  // Start the server
  err := (":8080")
  if err != nil {
    ("Failed to start server", err)
  }
}

GO Micro Example:

package main
​
import (
  "context"
  "/micro/go-micro"
  "/micro/go-micro/service/grpc"
  "your_project/common"
)
​
func main() {
  // Create a new service
  service := (
    ("example"),
  )
​
  // ...
​
  // Register the service
  if err := (); err != nil {
    ("Service registration failed", err)
  }
}

Read request example (Web service):

package main
​
import (
  "/gin-gonic/gin"
  "your_project/common"
)
​
func getUserHandler(c *) {
  // Reading parameters from the request
  userID := ("id")
​
  // Logging the received request
  ("Received request to fetch user with ID:", userID)
​
  // Perform necessary operations, ., fetch user from the database
​
  // Logging the completion of the request
  ("Request processed successfully")
​
  (200, {"message": "User fetched successfully"})
}
​
func main() {
  router := ()
​
  ("/user/:id", getUserHandler)
​
  // Start the server
  err := (":8080")
  if err != nil {
    ("Failed to start server", err)
  }
}

Passive acceptance request example (GO Micro):

package main
​
import (
  "context"
  "/micro/go-micro"
  "/micro/go-micro/service/grpc"
  "your_project/common"
)
​
// UserServiceHandler implements the UserService interface
type UserServiceHandler struct{}
​
func (u *UserServiceHandler) GetUser(ctx , req *UserRequest, res *UserResponse) error {
  // Log the received request
  ("Received GetUser request for user ID:", )
​
  // Perform necessary operations, ., fetch user from the database
​
  // Log the completion of the request
  ("GetUser request processed successfully")
​
  return nil
}
​
func main() {
  // Create a new service
  service := (
    ("example"),
  )
​
  // Register the service handler
  ()
  UserService := ()
  ().Handle(
    ().NewHandler(&UserServiceHandler{}),
  )
​
  // ...
​
  // Run the service
  if err := (); err != nil {
    ("Service registration failed", err)
  }
}

Example of reading message middleware (such as Kafka):

package main
​
import (
  "context"
  "/segmentio/kafka-go"
  "your_project/common"
)
​
func main() {
  r := ({
    // ...
  })
​
  for {
    m, err := (())
    if err != nil {
      ("Error reading message from Kafka", err)
      continue
    }
​
    // Process the message
    ("Message received:", string())
  }
}

Redis cache usage example:

package main
​
import (
  "context"
  "/go-redis/redis/v8"
  "your_project/common"
)
​
func main() {
  // ...
​
  // Example: Fetch data from Redis cache
  key := "example_key"
  val, err := ((), key).Result()
  if err ==  {
    // Cache miss
    ("Cache miss for key:", key)
  } else if err != nil {
    // Error accessing Redis cache
    ("Error accessing Redis cache:", err)
  } else {
    // Data retrieved successfully from cache
    ("Data retrieved from cache:", val)
  }
}

6. Selection and encapsulation of log library: Selecting a high-performance, structured log library, such as Zap, can improve the efficiency and readability of logging. Appropriate encapsulation of the log library, such as the examples in the common package provided, can simplify the use of logging and maintain code consistency.

In summary, the key to standardizing the use of GO language logs is to understand the meaning of log levels, select appropriate log levels according to actual conditions, maintain a consistent log format and a reasonable log segmentation and storage strategy. With proper logging, the maintenance and reliability of the project can be improved, making troubleshooting and system monitoring easier. The above example shows how to use the logging function in a real project in combination with specific scenarios.

The above is the detailed content shared by the standardized use of logs in Go language. For more information about Go logs, please pay attention to my other related articles!