Last active
September 20, 2020 07:50
-
-
Save shubhag/3ba1b478d58ffc27c7340c766d11de4f to your computer and use it in GitHub Desktop.
Custom writer working code
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
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"io" | |
"os" | |
"os/exec" | |
"time" | |
) | |
func main() { | |
w1 := &customWriter{w: os.Stdout, severity: "info"} | |
w2 := &customWriter{w: os.Stdout, severity: "error"} | |
args := []string{"-c", `echo "stdout message"; echo "stdout message"; >&2 echo "stderr message";`} | |
cmd := exec.Command("sh", args...) | |
cmd.Stdout = w1 | |
cmd.Stderr = w2 | |
err := cmd.Run() | |
if err != nil { | |
panic(err) | |
} | |
} | |
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