github.com/damirazo/docker@v1.9.0/pkg/jsonlog/jsonlog.go (about)

     1  package jsonlog
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"time"
     7  )
     8  
     9  // JSONLog represents a log message, typically a single entry from a given log stream.
    10  // JSONLogs can be easily serialized to and from JSON and support custom formatting.
    11  type JSONLog struct {
    12  	// Log is the log message
    13  	Log string `json:"log,omitempty"`
    14  	// Stream is the log source
    15  	Stream string `json:"stream,omitempty"`
    16  	// Created is the created timestamp of log
    17  	Created time.Time `json:"time"`
    18  }
    19  
    20  // Format returns the log formatted according to format
    21  // If format is nil, returns the log message
    22  // If format is json, returns the log marshalled in json format
    23  // By defalut, returns the log with the log time formatted according to format.
    24  func (jl *JSONLog) Format(format string) (string, error) {
    25  	if format == "" {
    26  		return jl.Log, nil
    27  	}
    28  	if format == "json" {
    29  		m, err := json.Marshal(jl)
    30  		return string(m), err
    31  	}
    32  	return fmt.Sprintf("%s %s", jl.Created.Format(format), jl.Log), nil
    33  }
    34  
    35  // Reset resets the log to nil.
    36  func (jl *JSONLog) Reset() {
    37  	jl.Log = ""
    38  	jl.Stream = ""
    39  	jl.Created = time.Time{}
    40  }