Created
June 8, 2018 07:16
-
-
Save broady/f70f01bc9e149aef793893aa4fd8a6a9 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 main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"time" | |
"github.com/broady/sdlog" | |
) | |
func init() { | |
fmt.Printf("sdlog: %v\n", sdlog.Default("cbro-scratch", "sdlog-example")) | |
} | |
func main() { | |
defer func() { | |
fmt.Printf("sdlog.Flush: %v\n", sdlog.Flush()) | |
}() | |
log.Print("hello there") | |
log.Print("hello there2") | |
fmt.Fprintln(os.Stderr, "this is to stderr") | |
time.Sleep(time.Second) | |
} |
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