From 154434f5a2c37f06fadbf323dc308edc3fb17485 Mon Sep 17 00:00:00 2001 From: Daniel Dao Date: Sun, 4 Oct 2015 21:07:09 +0000 Subject: [PATCH] add labels/env log option for jsonfile this allows jsonfile logger to collect extra metadata from containers with `--log-opt labels=label1,label2 --log-opt env=env1,env2`. Extra attributes are saved into `attrs` attributes for each log data. Signed-off-by: Daniel Dao --- jsonlog/jsonlogbytes.go | 13 +++++++++++++ jsonlog/jsonlogbytes_test.go | 2 ++ 2 files changed, 15 insertions(+) diff --git a/jsonlog/jsonlogbytes.go b/jsonlog/jsonlogbytes.go index b2b1f98..ff7aaf1 100644 --- a/jsonlog/jsonlogbytes.go +++ b/jsonlog/jsonlogbytes.go @@ -2,6 +2,7 @@ package jsonlog import ( "bytes" + "encoding/json" "unicode/utf8" ) @@ -12,6 +13,9 @@ type JSONLogs struct { Log []byte `json:"log,omitempty"` Stream string `json:"stream,omitempty"` Created string `json:"time"` + + // json-encoded bytes + RawAttrs json.RawMessage `json:"attrs,omitempty"` } // MarshalJSONBuf is based on the same method from JSONLog @@ -34,6 +38,15 @@ func (mj *JSONLogs) MarshalJSONBuf(buf *bytes.Buffer) error { buf.WriteString(`"stream":`) ffjsonWriteJSONString(buf, mj.Stream) } + if len(mj.RawAttrs) > 0 { + if first == true { + first = false + } else { + buf.WriteString(`,`) + } + buf.WriteString(`"attrs":`) + buf.Write(mj.RawAttrs) + } if first == true { first = false } else { diff --git a/jsonlog/jsonlogbytes_test.go b/jsonlog/jsonlogbytes_test.go index 6c36828..6d6ad21 100644 --- a/jsonlog/jsonlogbytes_test.go +++ b/jsonlog/jsonlogbytes_test.go @@ -21,6 +21,8 @@ func TestJSONLogsMarshalJSONBuf(t *testing.T) { &JSONLogs{Log: []byte("\u2028 \u2029")}: `^{\"log\":\"\\u2028 \\u2029\",\"time\":}$`, &JSONLogs{Log: []byte{0xaF}}: `^{\"log\":\"\\ufffd\",\"time\":}$`, &JSONLogs{Log: []byte{0x7F}}: `^{\"log\":\"\x7f\",\"time\":}$`, + // with raw attributes + &JSONLogs{Log: []byte("A log line"), RawAttrs: []byte(`{"hello":"world","value":1234}`)}: `^{\"log\":\"A log line\",\"attrs\":{\"hello\":\"world\",\"value\":1234},\"time\":}$`, } for jsonLog, expression := range logs { var buf bytes.Buffer