gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/log/json_k8s.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 "runtime" 21 "strings" 22 "time" 23 ) 24 25 type k8sJSONLog struct { 26 Log string `json:"log"` 27 Level Level `json:"level"` 28 Time time.Time `json:"time"` 29 } 30 31 // K8sJSONEmitter logs messages in json format that is compatible with 32 // Kubernetes fluent configuration. 33 type K8sJSONEmitter struct { 34 *Writer 35 } 36 37 // Emit implements Emitter.Emit. 38 func (e K8sJSONEmitter) Emit(depth int, level Level, timestamp time.Time, format string, v ...any) { 39 logLine := fmt.Sprintf(format, v...) 40 if _, file, line, ok := runtime.Caller(depth + 1); ok { 41 if slash := strings.LastIndexByte(file, byte('/')); slash >= 0 { 42 file = file[slash+1:] // Trim any directory path from the file. 43 } 44 logLine = fmt.Sprintf("%s:%d] %s", file, line, logLine) 45 } 46 j := k8sJSONLog{ 47 Log: logLine, 48 Level: level, 49 Time: timestamp, 50 } 51 b, err := json.Marshal(j) 52 if err != nil { 53 panic(err) 54 } 55 e.Writer.Write(b) 56 }