Skip to content

Instantly share code, notes, and snippets.

@broady
Last active May 26, 2018 00:36
Show Gist options
  • Save broady/859d32c0760b1ebfd65022369d4bd3c2 to your computer and use it in GitHub Desktop.
Save broady/859d32c0760b1ebfd65022369d4bd3c2 to your computer and use it in GitHub Desktop.
package sdlog
import (
"bufio"
"context"
"errors"
"fmt"
"os"
"syscall"
"cloud.google.com/go/logging"
)
var logger *logging.Logger
func Init(c *logging.Client, logID string, opts ...logging.LoggerOption) error {
if logger != nil {
return errors.New("sdlog: already initialized")
}
return redirect(c, logID)
}
func Default(parent string, logID string, opts ...logging.LoggerOption) error {
if logger != nil {
return errors.New("sdlog: already initialized")
}
ctx := context.Background()
c, err := logging.NewClient(ctx, parent)
if err != nil {
return err
}
return redirect(c, logID)
}
func Flush() error {
if logger == nil {
return errors.New("sdlog: not initialized; not flushing")
}
return logger.Flush()
}
func redirect(client *logging.Client, logID string, opts ...logging.LoggerOption) error {
r, w, err := os.Pipe()
if err != nil {
return err
}
br := bufio.NewReader(r)
logger = client.Logger(logID, opts...)
if err := syscall.Dup2(int(w.Fd()), 2); err != nil {
return fmt.Errorf("dup2: %v", err)
}
go func() {
for {
line, err := br.ReadString('\n')
if err != nil {
fmt.Fprintf(os.Stdout, "sdlog: pipe fail: %v", err)
continue
}
fmt.Fprintf(os.Stdout, "sdlog: writing %q\n", line)
logger.Log(logging.Entry{Payload: line})
}
}()
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment