forked from cncf/devstats.archive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
77 lines (70 loc) · 1.77 KB
/
log.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package gha2db
import (
"database/sql"
"fmt"
"strings"
"sync"
"time"
)
// Holds data needed to make DB calls
type logContext struct {
ctx Ctx
con *sql.DB
}
// This is the *only* global variable used in entire toolset.
// I want to save passing context and DB to all Printf(...) calls.
// This variable is initialized *only* once, and must be guared by the mutex
// to avoid initializing it from multiple go routines
var (
logCtx *logContext
logCtxMutex sync.Mutex
)
// Returns new context when not yet created
func newLogContext() *logContext {
var ctx Ctx
ctx.Init()
con := PgConn(&ctx)
return &logContext{ctx: ctx, con: con}
}
// logToDB writes message to database
func logToDB(format string, args ...interface{}) (err error) {
if logCtx.ctx.LogToDB == false {
return
}
msg := strings.Replace(fmt.Sprintf(format, args...), "\n", " ", -1)
_, err = ExecSQL(
logCtx.con,
&logCtx.ctx,
"insert into gha_logs(msg) "+NValues(1),
msg,
)
return
}
// Printf is a wrapper around Printf(...) that supports logging.
func Printf(format string, args ...interface{}) (n int, err error) {
// Initialize context once
if logCtx == nil {
logCtxMutex.Lock()
if logCtx == nil {
logCtx = newLogContext()
fmt.Printf("%v: Initialized DB logs\n", time.Now())
}
logCtxMutex.Unlock()
}
// Avoid query out on adding to logs itself
// it would print any text with its particular logs DB insert which
// would result in stdout mess
qOut := logCtx.ctx.QOut
logCtx.ctx.QOut = false
defer func() {
logCtx.ctx.QOut = qOut
}()
// Actual logging to stdout & DB
if logCtx.ctx.LogTime {
n, err = fmt.Printf("%s: "+format, append([]interface{}{ToYMDHMSDate(time.Now())}, args...)...)
} else {
n, err = fmt.Printf(format, args...)
}
err = logToDB(format, args...)
return
}