Last active
September 20, 2020 07:44
-
-
Save shubhag/b0216c82409dda519685ebfc2dd3e354 to your computer and use it in GitHub Desktop.
Custom io.writer with extra debug information
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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