How to Output Logs to Both File and Console in go-zero?

To output logs to both a file and the console while using the go-zero framework, follow these steps to configure and write your code.

Steps:

  1. Create the configuration file config.yaml: First, define a YAML file to configure the logging mode and encoding format.
  1. Mode: file
  2. Encoding: json
  1. Write the main program main.go: Use the following Go code to load the configuration file and set up logging to both a file and the console.
  1. package main
  2. import (
  3. "os"
  4. "time"
  5. "github.com/zeromicro/go-zero/core/conf"
  6. "github.com/zeromicro/go-zero/core/logx"
  7. "github.com/zeromicro/go-zero/core/proc"
  8. )
  9. func main() {
  10. var c logx.LogConf
  11. conf.MustLoad("config.yaml", &c) // Load the configuration file
  12. logx.MustSetup(c) // Set up the logging configuration
  13. logx.AddWriter(logx.NewWriter(os.Stdout)) // Add console output
  14. for {
  15. select {
  16. case <-proc.Done(): // Check if the program needs to exit
  17. return
  18. default:
  19. time.Sleep(time.Second)
  20. logx.Info(time.Now()) // Log the current time
  21. }
  22. }
  23. }

Detailed Explanation:

  • Configuration File (config.yaml):

    • Mode: file specifies that logs should be output to a file.
    • Encoding: json specifies that the log format will be JSON.
  • Main Program (main.go):

    • Use conf.MustLoad to load the configuration file.
    • Call logx.MustSetup to configure the logging system.
    • Use logx.AddWriter to add an additional logging target. Here, we add standard output (console).
    • In an infinite loop, record the current time every second. The select statement combined with proc.Done() allows for smooth program termination.

By following the above configuration and code, you can achieve log output to both a file and the console in go-zero.