Skip to content

Commit db219be

Browse files
author
Francesc Campoy
committed
handle signals correctly
Change-Id: Ida075f41113c30b4ec1a12f90ab2e6a4d57eba97
1 parent 7198858 commit db219be

File tree

1 file changed

+32
-11
lines changed

1 file changed

+32
-11
lines changed

logpipe.go

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"fmt"
2222
"io"
2323
"os"
24+
"os/signal"
2425

2526
flags "github.com/jessevdk/go-flags"
2627

@@ -41,10 +42,10 @@ func main() {
4142
// Check if Standard In is coming from a pipe
4243
fi, err := os.Stdin.Stat()
4344
if err != nil {
44-
errorf("Could not stat standard input: %v\n", err)
45+
errorf("Could not stat standard input: %v", err)
4546
}
4647
if fi.Mode()&os.ModeNamedPipe == 0 {
47-
errorf("Nothing is piped in so there is nothing to log!\n")
48+
errorf("Nothing is piped in so there is nothing to log!")
4849
}
4950

5051
// Creates a client.
@@ -53,27 +54,47 @@ func main() {
5354
if err != nil {
5455
errorf("Failed to create client: %v", err)
5556
}
56-
5757
// Selects the log to write to.
5858
logger := client.Logger(opts.LogName)
5959

60-
// Read from Stdin and log it to Stdout and Stackdriver
61-
s := bufio.NewScanner(io.TeeReader(os.Stdin, os.Stdout))
62-
for s.Scan() {
63-
logger.Log(logging.Entry{Payload: s.Text()})
60+
lines := make(chan string)
61+
go func() {
62+
defer close(lines)
63+
// Read from Stdin and log it to Stdout and Stackdriver
64+
s := bufio.NewScanner(io.TeeReader(os.Stdin, os.Stdout))
65+
for s.Scan() {
66+
lines <- s.Text()
67+
}
68+
if err := s.Err(); err != nil {
69+
fmt.Fprintf(os.Stderr, "Failed to scan input: %v\n", err)
70+
}
71+
}()
72+
73+
signals := make(chan os.Signal)
74+
signal.Notify(signals, os.Interrupt)
75+
76+
loop:
77+
for {
78+
select {
79+
case line, ok := <-lines:
80+
if !ok {
81+
break loop
82+
}
83+
logger.Log(logging.Entry{Payload: line})
84+
case s := <-signals:
85+
fmt.Fprintf(os.Stderr, "Terminating program after received signal: %v\n", s)
86+
break loop
87+
}
6488
}
6589

6690
// Closes the client and flushes the buffer to the Stackdriver Logging
6791
// service.
6892
if err := client.Close(); err != nil {
6993
errorf("Failed to close client: %v", err)
7094
}
71-
if err := s.Err(); err != nil {
72-
errorf("Failed to scan input: %v", err)
73-
}
7495
}
7596

7697
func errorf(format string, args ...interface{}) {
77-
fmt.Fprintf(os.Stderr, format, args...)
98+
fmt.Fprintf(os.Stderr, format+"\n", args...)
7899
os.Exit(2)
79100
}

0 commit comments

Comments
 (0)