-
Notifications
You must be signed in to change notification settings - Fork 33
/
common.go
50 lines (39 loc) · 1.11 KB
/
common.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main
import (
"log"
"os"
"os/signal"
"syscall"
"time"
"golang.org/x/net/context"
)
const timeFormat = "03:04:05 PM"
func ClientLogf(ts time.Time, format string, args ...interface{}) {
log.Printf("[%s] <<Client>>: "+format, append([]interface{}{ts.Format(timeFormat)}, args...)...)
}
func ServerLogf(ts time.Time, format string, args ...interface{}) {
log.Printf("[%s] <<Server>>: "+format, append([]interface{}{ts.Format(timeFormat)}, args...)...)
}
func MessageLog(ts time.Time, name, msg string) {
log.Printf("[%s] %s: %s", ts.Format(timeFormat), name, msg)
}
func DebugLogf(format string, args ...interface{}) {
if !debugMode {
return
}
log.Printf("[%s] <<Debug>>: "+format, append([]interface{}{time.Now().Format(timeFormat)}, args...)...)
}
func SignalContext(ctx context.Context) context.Context {
ctx, cancel := context.WithCancel(ctx)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
DebugLogf("listening for shutdown signal")
<-sigs
DebugLogf("shutdown signal received")
signal.Stop(sigs)
close(sigs)
cancel()
}()
return ctx
}