@@ -20,6 +20,7 @@ import (
2020 "io"
2121 "log"
2222 "os"
23+ "os/signal"
2324
2425 flags "github.com/jessevdk/go-flags"
2526
@@ -52,14 +53,43 @@ func main() {
5253 if err != nil {
5354 log .Fatalf ("Failed to create client: %v" , err )
5455 }
56+ errc := make (chan error )
57+ client .OnError = func (err error ) { errc <- err }
5558
5659 // Selects the log to write to.
5760 logger := client .Logger (opts .LogName )
5861
5962 // Read from Stdin and log it to Stdout and Stackdriver
60- s := bufio .NewScanner (io .TeeReader (os .Stdin , os .Stdout ))
61- for s .Scan () {
62- logger .Log (logging.Entry {Payload : s .Text ()})
63+ lines := make (chan string )
64+ go func () {
65+ s := bufio .NewScanner (io .TeeReader (os .Stdin , os .Stdout ))
66+ for s .Scan () {
67+ lines <- s .Text ()
68+ }
69+ if err := s .Err (); err != nil {
70+ errc <- fmt .Errorf ("could not read from std in: %v" , err )
71+ }
72+ close (lines )
73+ }()
74+
75+ signals := make (chan os.Signal )
76+ signal .Notify (signals , os .Interrupt )
77+
78+ mainLoop:
79+ for {
80+ select {
81+ case line , ok := <- lines :
82+ if ! ok {
83+ break mainLoop
84+ }
85+ logger .Log (logging.Entry {Payload : line })
86+ case err := <- errc :
87+ log .Printf ("error received: %v" , err )
88+ break mainLoop
89+ case <- signals :
90+ fmt .Fprintln (os .Stderr , "received interrupt: exiting program" )
91+ break mainLoop
92+ }
6393 }
6494
6595 // Closes the client and flushes the buffer to the Stackdriver Logging
@@ -68,9 +98,5 @@ func main() {
6898 log .Fatalf ("Failed to close client: %v" , err )
6999 }
70100
71- if err := s .Err (); err != nil {
72- log .Fatalf ("Failed to scan input: %v" , err )
73- }
74-
75- log .Println ("Finished logging" )
101+ fmt .Fprintln (os .Stderr , "Finished logging" )
76102}
0 commit comments