go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/tsmon/monitor/debug.go (about) 1 // Copyright 2015 The LUCI 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 monitor 16 17 import ( 18 "context" 19 "os" 20 21 "github.com/golang/protobuf/proto" 22 23 "go.chromium.org/luci/common/clock" 24 "go.chromium.org/luci/common/logging" 25 pb "go.chromium.org/luci/common/tsmon/ts_mon_proto" 26 "go.chromium.org/luci/common/tsmon/types" 27 ) 28 29 type debugMonitor struct { 30 path string 31 } 32 33 // NewDebugMonitor returns a Monitor that outputs metrics to a log, and 34 // optionally a file on disk. 35 func NewDebugMonitor(path string) Monitor { 36 return &debugMonitor{ 37 path: path, 38 } 39 } 40 41 func (m *debugMonitor) ChunkSize() int { 42 return 0 43 } 44 45 func (m *debugMonitor) Send(ctx context.Context, cells []types.Cell) error { 46 str := proto.MarshalTextString(&pb.MetricsPayload{ 47 MetricsCollection: SerializeCells(cells, clock.Now(ctx)), 48 }) 49 50 logging.Infof(ctx, "Sending ts_mon metrics:\n%s", str) 51 52 if m.path != "" { 53 file, err := os.OpenFile(m.path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0664) 54 if err != nil { 55 logging.Errorf(ctx, "Failed to open file %s: %s", m.path, err) 56 return err 57 } 58 59 defer func() { 60 if err := file.Close(); err != nil { 61 logging.Errorf(ctx, "Failed to close file %s: %s", m.path, err) 62 } 63 }() 64 65 if _, err = file.WriteString(str); err != nil { 66 logging.Errorf(ctx, "Failed to write to the file %s: %s", m.path, err) 67 return err 68 } 69 } 70 71 return nil 72 } 73 74 func (m *debugMonitor) Close() error { 75 return nil 76 }