Last active
May 26, 2018 00:36
-
-
Save broady/859d32c0760b1ebfd65022369d4bd3c2 to your computer and use it in GitHub Desktop.
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 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