git » chasquid » commit 7eba9bb

chasquid: Flush logs periodically and before exiting

author Alberto Bertogli
2016-07-22 00:42:21 UTC
committer Alberto Bertogli
2016-08-01 21:56:57 UTC
parent ae1c246bde804a26bd60f66be47ad8eaf1bd01ef

chasquid: Flush logs periodically and before exiting

This patch makes chasquid flush logs periodically, and also before exiting,
even if it gets killed via the usual signals (including Ctrl-C).

Both things help troubleshooting when there is not much traffic, or we kill
the server manually (including during automated tests).

chasquid.go +26 -0

diff --git a/chasquid.go b/chasquid.go
index ba1065e..7fecaae 100644
--- a/chasquid.go
+++ b/chasquid.go
@@ -13,8 +13,10 @@ import (
 	"net/mail"
 	"net/textproto"
 	"os"
+	"os/signal"
 	"path/filepath"
 	"strings"
+	"syscall"
 	"time"
 
 	"blitiri.com.ar/go/chasquid/internal/auth"
@@ -44,6 +46,11 @@ var (
 func main() {
 	flag.Parse()
 
+	setupSignalHandling()
+
+	defer glog.Flush()
+	go periodicallyFlushLogs()
+
 	// Seed the PRNG, just to prevent for it to be totally predictable.
 	rand.Seed(time.Now().UnixNano())
 
@@ -134,6 +141,25 @@ func loadDomain(s *Server, name, dir string) {
 	}
 }
 
+// Flush logs periodically, to help troubleshooting if there isn't that much
+// traffic.
+func periodicallyFlushLogs() {
+	for range time.Tick(5 * time.Second) {
+		glog.Flush()
+	}
+}
+
+// Set up signal handling, to flush logs when we get killed.
+func setupSignalHandling() {
+	c := make(chan os.Signal, 1)
+	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
+	go func() {
+		<-c
+		glog.Flush()
+		os.Exit(1)
+	}()
+}
+
 type Server struct {
 	// Main hostname, used for display only.
 	Hostname string