Expose logger (#34)

This closes #13 and gives ability to set your own logger with your custom prefixes and other logic.

Done:
- New function `SetLogger` added to be able to set logger
- Flag `gracehttp.log` removed just not to confuse people with logs from nowhere
This commit is contained in:
Maksim N 2017-02-16 23:22:40 +01:00 committed by Naitik Shah
parent 5729e48447
commit 5b49dc98ff
2 changed files with 13 additions and 14 deletions

View File

@ -5,7 +5,6 @@ package gracehttp
import ( import (
"bytes" "bytes"
"crypto/tls" "crypto/tls"
"flag"
"fmt" "fmt"
"log" "log"
"net" "net"
@ -20,7 +19,7 @@ import (
) )
var ( var (
verbose = flag.Bool("gracehttp.log", true, "Enable logging.") logger *log.Logger
didInherit = os.Getenv("LISTEN_FDS") != "" didInherit = os.Getenv("LISTEN_FDS") != ""
ppid = os.Getppid() ppid = os.Getppid()
) )
@ -129,17 +128,17 @@ func Serve(servers ...*http.Server) error {
} }
// Some useful logging. // Some useful logging.
if *verbose { if logger != nil {
if didInherit { if didInherit {
if ppid == 1 { if ppid == 1 {
log.Printf("Listening on init activated %s", pprintAddr(a.listeners)) logger.Printf("Listening on init activated %s", pprintAddr(a.listeners))
} else { } else {
const msg = "Graceful handoff of %s with new pid %d and old pid %d" const msg = "Graceful handoff of %s with new pid %d and old pid %d"
log.Printf(msg, pprintAddr(a.listeners), os.Getpid(), ppid) logger.Printf(msg, pprintAddr(a.listeners), os.Getpid(), ppid)
} }
} else { } else {
const msg = "Serving %s with pid %d" const msg = "Serving %s with pid %d"
log.Printf(msg, pprintAddr(a.listeners), os.Getpid()) logger.Printf(msg, pprintAddr(a.listeners), os.Getpid())
} }
} }
@ -166,8 +165,8 @@ func Serve(servers ...*http.Server) error {
} }
return err return err
case <-waitdone: case <-waitdone:
if *verbose { if logger != nil {
log.Printf("Exiting pid %d.", os.Getpid()) logger.Printf("Exiting pid %d.", os.Getpid())
} }
return nil return nil
} }
@ -184,3 +183,8 @@ func pprintAddr(listeners []net.Listener) []byte {
} }
return out.Bytes() return out.Bytes()
} }
// SetLogger sets logger to be able to grab some useful logs
func SetLogger(l *log.Logger) {
logger = l
}

View File

@ -113,11 +113,6 @@ func testbinMain() {
}, },
} }
err := flag.Set("gracehttp.log", "false")
if err != nil {
log.Fatalf("Error setting gracehttp.log: %s", err)
}
// print json to stderr once we can successfully connect to all three // print json to stderr once we can successfully connect to all three
// addresses. the ensures we only print the line once we're ready to serve. // addresses. the ensures we only print the line once we're ready to serve.
go func() { go func() {
@ -133,7 +128,7 @@ func testbinMain() {
} }
}() }()
err = gracehttp.Serve( err := gracehttp.Serve(
&http.Server{Addr: httpAddr, Handler: newHandler()}, &http.Server{Addr: httpAddr, Handler: newHandler()},
httpsServer(httpsAddr), httpsServer(httpsAddr),
) )