Skip to content
KerwinKoo edited this page Jan 25, 2016 · 12 revisions

Goa日志

Goa的日志格式固定,如测试代码的mount日志:

INFO[01-25|09:56:34] mount      app=API ctrl=Operands action=Add route="GET /add/:left/:right"

依次为:

  • 日志类型
  • 日志时间
  • 行为名称
  • 日志内容

其中日志内容是以key=value的形式存在。

Logger接口的实现写在包gopkg.in/inconshreveable/log15.v2,Goa将其重命名为log:

// A Logger writes key/value pairs to a Handler
type Logger interface {
	// New returns a new Logger that has this logger's context plus the given context
	New(ctx ...interface{}) Logger

	// SetHandler updates the logger to write records to the specified handler.
	SetHandler(h Handler)

	// Log a message at the given level with context key/value pairs
	Debug(msg string, ctx ...interface{})
	Info(msg string, ctx ...interface{})
	Warn(msg string, ctx ...interface{})
	Error(msg string, ctx ...interface{})
	Crit(msg string, ctx ...interface{})
}

具体调用方法为:

service.Info("mount", "ctrl", "Operands", "action", "Add", "route", "GET /add/:left/:right")

第一个是日志的名字,其他必须是成对出现,每对为对应的key=value。

注意

  • Goa不支持日志存储,因为对日志存储的需求因人而异。为不影响访问速度,建议自省实现异步的日志存储,可以使用MQ。

Goa Media

使用Goa的Media之前,首先得明白其存在的意义。

当终端访问我们的HTTP API时,应有一个双方约定好的信息格式载体,我们以常用的JSON为例。Response body信息为JSON,同时server端反馈的信息也应该是JSON。在Go代码里,JSON的本质是一个type为string的key-value的map,代码表述为:

map[string]interface{}

其中interface接受各种类型。

当我们需要实现这么一个map时,最规范也是最常用的办法,就是将此段JSON的模板结构体直接赋值转换为map。

因此,go生成API-JSON返回信息的基本流程为:

  • 1.定义结构体&定义该结构体对应的JSON模板
  • 2.为结构体变量赋值
  • 3.将结构体变量映射到JSON模板中,生成JSON型map
  • 4.将此map(已成为JSON)返回给终端

[[TOC]]

Clone this wiki locally