-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
50 lines (46 loc) · 1.19 KB
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Package JSON formats log outputs into JSON using
// the structure { "context": {}, "message": "message" }
//
// Note that the encoding/json package used underneath
// does not work with embbeded structures until the go
// issue https://github.com/golang/go/issues/6213
// is solved.
//
// A temporary solution is to define the MarshalJSON() ([]byte, error)
// method on the context type.
//
// Example:
//
// func (c Context) MarshalJSON() ([]byte, error) {
// return libjson.Marshal(struct {
// Time libtime.Time `json:"time"`
// Level level.Level `json:"level"`
// }{
// Time: c.WithTime.Time(),
// Level: c.WithLevel.Level(),
// })
// }
package json
import (
"bytes"
"encoding/json"
"strings"
)
// FormatJSON format into JSON using the structure
// { "context": v, "message": msg }
func JSON(v interface{}, msg string) (string, error) {
m := struct {
Context interface{} `json:"context"`
Message string `json:"message"`
}{
Context: v,
Message: msg,
}
buf := bytes.Buffer{}
enc := json.NewEncoder(&buf)
if err := enc.Encode(m); err != nil {
return "", err
}
// Trim the last newline character added by json.Encoder
return strings.TrimSuffix(buf.String(), "\n"), nil
}