| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
package log |
| 16 |
|
| 17 |
import ( |
| 18 |
"encoding/json" |
| 19 |
"fmt" |
| 20 |
"time" |
| 21 |
) |
| 22 |
|
| 23 |
type jsonLog struct { |
| 24 |
Msg string `json:"msg"` |
| 25 |
Level Level `json:"level"` |
| 26 |
Time time.Time `json:"time"` |
| 27 |
} |
| 28 |
|
| 29 |
|
| 30 |
func (l Level) MarshalJSON() ([]byte, error) { |
| 31 |
switch l { |
| 32 |
case Warning: |
| 33 |
return []byte(`"warning"`), nil |
| 34 |
case Info: |
| 35 |
return []byte(`"info"`), nil |
| 36 |
case Debug: |
| 37 |
return []byte(`"debug"`), nil |
| 38 |
default: |
| 39 |
return nil, fmt.Errorf("unknown level %v", l) |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
func (l *Level) UnmarshalJSON(b []byte) error { |
| 46 |
switch s := string(b); s { |
| 47 |
case "0", `"warning"`: |
| 48 |
*l = Warning |
| 49 |
case "1", `"info"`: |
| 50 |
*l = Info |
| 51 |
case "2", `"debug"`: |
| 52 |
*l = Debug |
| 53 |
default: |
| 54 |
return fmt.Errorf("unknown level %q", s) |
| 55 |
} |
| 56 |
return nil |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
type JSONEmitter struct { |
| 61 |
*Writer |
| 62 |
} |
| 63 |
|
| 64 |
|
| 65 |
func (e JSONEmitter) Emit(_ int, level Level, timestamp time.Time, format string, v ...interface{}) { |
| 66 |
j := jsonLog{ |
| 67 |
Msg: fmt.Sprintf(format, v...), |
| 68 |
Level: level, |
| 69 |
Time: timestamp, |
| 70 |
} |
| 71 |
b, err := json.Marshal(j) |
| 72 |
if err != nil { |
| 73 |
panic(err) |
| 74 |
} |
| 75 |
e.Writer.Write(b) |
| 76 |
} |