glog is very friendly to log analysis tools and supports outputting logs in JSON format for easier parsing and analysis of log content later on.

Using map/struct Parameters

Supporting JSON data format log output is very simple; just provide a map or struct type parameter to the printing method.

Example usage:

  1. package main
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/frame/g"
  5. )
  6. func main() {
  7. ctx := context.TODO()
  8. g.Log().Debug(ctx, g.Map{"uid": 100, "name": "john"})
  9. type User struct {
  10. Uid int `json:"uid"`
  11. Name string `json:"name"`
  12. }
  13. g.Log().Debug(ctx, User{100, "john"})
  14. }

After execution, the terminal outputs:

  1. 2019-06-02 15:28:52.653 [DEBU] {"name":"john","uid":100}
  2. 2019-06-02 15:28:52.653 [DEBU] {"uid":100,"name":"john"}

Combining gjson.MustEncode

Additionally, you can achieve JSON content output in conjunction with gjson.MustEncode, for example:

  1. package main
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/encoding/gjson"
  5. "github.com/gogf/gf/v2/frame/g"
  6. )
  7. func main() {
  8. ctx := context.TODO()
  9. type User struct {
  10. Uid int `json:"uid"`
  11. Name string `json:"name"`
  12. }
  13. g.Log().Debugf(ctx, `user json: %s`, gjson.MustEncode(User{100, "john"}))
  14. }

After execution, the terminal outputs:

  1. 2022-04-25 18:09:45.029 [DEBU] user json: {"uid":100,"name":"john"}