github.com/chenbh/concourse/v6@v6.4.2/fly/eventstream/timestamped_writer.go (about) 1 package eventstream 2 3 import ( 4 "bytes" 5 "io" 6 "time" 7 ) 8 9 type TimestampedWriter struct { 10 showTimestamp bool 11 time []byte 12 writer io.Writer 13 newLine bool 14 } 15 16 func (w *TimestampedWriter) Write(b []byte) (int, error) { 17 var toWrite []byte 18 19 for _, c := range b { 20 if w.showTimestamp && w.newLine { 21 toWrite = append(toWrite, w.time...) 22 } 23 24 toWrite = append(toWrite, c) 25 26 w.newLine = c == '\n' 27 } 28 29 _, err := w.writer.Write(toWrite) 30 if err != nil { 31 return 0, err 32 } 33 34 return len(b), nil 35 } 36 37 func NewTimestampedWriter(writer io.Writer, showTime bool) *TimestampedWriter { 38 return &TimestampedWriter{ 39 showTimestamp: showTime, 40 writer: writer, 41 newLine: showTime, 42 } 43 } 44 45 func (w *TimestampedWriter) SetTimestamp(time int64) { 46 if w.showTimestamp { 47 var b bytes.Buffer 48 if time != 0 { 49 b.WriteString(getUnixTimeAsString(time)) 50 } else { 51 b.WriteString(createEmptyString(8)) 52 } 53 b.WriteString(createEmptyString(2)) 54 55 w.time = b.Bytes() 56 } 57 } 58 59 func getUnixTimeAsString(timestamp int64) string { 60 const posixTimeLayout string = "15:04:05" 61 return time.Unix(timestamp, 0).Format(posixTimeLayout) 62 } 63 64 func createEmptyString(length int) string { 65 const charset = " " 66 b := make([]byte, length) 67 for i := range b { 68 b[i] = charset[0] 69 } 70 return string(b) 71 }