Skip to content

Instantly share code, notes, and snippets.

@KushalP
Last active December 25, 2015 13:19
Show Gist options
  • Save KushalP/6982477 to your computer and use it in GitHub Desktop.
Save KushalP/6982477 to your computer and use it in GitHub Desktop.
Currently, log output in docker is broken as it parses JSON strings and escapes them. Instead it should be nesting them within the struct that's used and cleanly exposing them as raw JSON. Here's an example that does this.
package main
import (
"encoding/json"
"fmt"
"time"
)
type JSONMessage struct {
Log interface{} `json:"log,omitempty"`
Created time.Time `json:"time,omitempty"`
}
func escapeLog(line string) (*json.RawMessage, error) {
var objmap *json.RawMessage
return objmap, json.Unmarshal([]byte(line), &objmap)
}
func CreateJSONMessage(line string) JSONMessage {
message := JSONMessage{
Log: line,
Created: time.Now(),
}
// convert our string into a json.RawMessage if it's a
// string containing valid JSON.
log, err := escapeLog(line)
if err == nil {
(&message).Log = log
}
return message
}
func main() {
logs := []string{
`{"a": {"b": "c"}}`,
"POST /login HTTP/1.1",
}
for _, element := range logs {
message := CreateJSONMessage(element)
output, err := json.Marshal(&message)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(output))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment