github.com/MerlinKodo/gvisor@v0.0.0-20231110090155-957f62ecf90e/pkg/log/json.go (about)

     1  // Copyright 2018 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    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  // MarshalJSON implements json.Marshaler.MarashalJSON.
    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  // UnmarshalJSON implements json.Unmarshaler.UnmarshalJSON.  It can unmarshal
    44  // from both string names and integers.
    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  // JSONEmitter logs messages in json format.
    60  type JSONEmitter struct {
    61  	*Writer
    62  }
    63  
    64  // Emit implements Emitter.Emit.
    65  func (e JSONEmitter) Emit(_ int, level Level, timestamp time.Time, format string, v ...any) {
    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  }