Skip to content

Instantly share code, notes, and snippets.

@shubhag
Last active September 20, 2020 07:44
Show Gist options
  • Save shubhag/b0216c82409dda519685ebfc2dd3e354 to your computer and use it in GitHub Desktop.
Save shubhag/b0216c82409dda519685ebfc2dd3e354 to your computer and use it in GitHub Desktop.
Custom io.writer with extra debug information
type line struct {
Message string
Timestamp time.Time
Severity string
}
type customWriter struct {
w io.Writer
severity string
}
func (e customWriter) Write(p []byte) (int, error) {
l := &line{
Message: string(p),
Timestamp: time.Now().UTC(),
Severity: e.severity,
}
buf := new(bytes.Buffer)
json.NewEncoder(buf).Encode(l)
data := buf.Bytes()
n, err := e.w.Write(data)
if err != nil {
return n, err
}
if n != len(data) {
return n, io.ErrShortWrite
}
return len(p), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment