|
| 1 | +/* |
| 2 | + Copyright 2017, Google, Inc. |
| 3 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | + you may not use this file except in compliance with the License. |
| 5 | + You may obtain a copy of the License at |
| 6 | +
|
| 7 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +
|
| 9 | + Unless required by applicable law or agreed to in writing, software |
| 10 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | + See the License for the specific language governing permissions and |
| 13 | + limitations under the License. |
| 14 | +*/ |
| 15 | + |
| 16 | +// Command logpipe is a service that will let you pipe logs directly to Stackdriver Logging. |
| 17 | +package main |
| 18 | + |
| 19 | +import ( |
| 20 | + "bufio" |
| 21 | + "fmt" |
| 22 | + "log" |
| 23 | + "os" |
| 24 | + |
| 25 | + flags "github.com/jessevdk/go-flags" |
| 26 | + |
| 27 | + "cloud.google.com/go/logging" |
| 28 | + "golang.org/x/net/context" |
| 29 | +) |
| 30 | + |
| 31 | +func main() { |
| 32 | + ctx := context.Background() |
| 33 | + |
| 34 | + var opts struct { |
| 35 | + ProjectID string `short:"p" long:"project" description:"Google Cloud Platform Project ID" required:"true"` |
| 36 | + LogName string `short:"l" long:"logname" description:"The name of the log to write to" default:"default"` |
| 37 | + } |
| 38 | + |
| 39 | + flags.Parse(&opts) |
| 40 | + |
| 41 | + projectID := &opts.ProjectID |
| 42 | + logName := &opts.LogName |
| 43 | + |
| 44 | + if *projectID == "" { |
| 45 | + fmt.Printf("Please specify a project ID\n") |
| 46 | + return |
| 47 | + } |
| 48 | + |
| 49 | + // Check if Standard In is coming from a pipe |
| 50 | + fi, err := os.Stdin.Stat() |
| 51 | + if err != nil { |
| 52 | + panic(err) |
| 53 | + } |
| 54 | + if fi.Mode()&os.ModeNamedPipe == 0 { |
| 55 | + fmt.Printf("Nothing is piped in so there is nothing to log!\n") |
| 56 | + return |
| 57 | + } |
| 58 | + |
| 59 | + // Creates a client. |
| 60 | + client, err := logging.NewClient(ctx, *projectID) |
| 61 | + if err != nil { |
| 62 | + log.Fatalf("Failed to create client: %v", err) |
| 63 | + } |
| 64 | + |
| 65 | + // Selects the log to write to. |
| 66 | + logger := client.Logger(*logName) |
| 67 | + |
| 68 | + // Read from Stdin and log it to Stdout and Stackdriver |
| 69 | + scanner := bufio.NewScanner(os.Stdin) |
| 70 | + for scanner.Scan() { |
| 71 | + text := scanner.Text() |
| 72 | + fmt.Println(text) |
| 73 | + logger.Log(logging.Entry{Payload: text}) |
| 74 | + } |
| 75 | + |
| 76 | + // Closes the client and flushes the buffer to the Stackdriver Logging |
| 77 | + // service. |
| 78 | + if err := client.Close(); err != nil { |
| 79 | + log.Fatalf("Failed to close client: %v", err) |
| 80 | + } |
| 81 | + |
| 82 | + fmt.Printf("Finished logging\n") |
| 83 | +} |
0 commit comments