You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
1.8 KiB
Go
87 lines
1.8 KiB
Go
2 years ago
|
package logging
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"log"
|
||
|
"os"
|
||
|
"strconv"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
func getLogType() string {
|
||
|
if t, ok := os.LookupEnv("LOGTYPE"); ok {
|
||
|
return t
|
||
|
}
|
||
|
return "DEFAULT"
|
||
|
}
|
||
|
|
||
|
func getVerbosity() int {
|
||
|
v := os.Getenv("VERBOSE")
|
||
|
level := 0
|
||
|
if v != "" {
|
||
|
var err error
|
||
|
level, err = strconv.Atoi(v)
|
||
|
if err != nil {
|
||
|
log.Fatalf("Invalid Verbosity %v", v)
|
||
|
}
|
||
|
}
|
||
|
return level
|
||
|
}
|
||
|
|
||
|
type logTopic string
|
||
|
|
||
|
const (
|
||
|
// define 4 character topic abbreviations for coloring
|
||
|
DError logTopic = "ERRO"
|
||
|
DClient logTopic = "CLNT"
|
||
|
DStart logTopic = "STRT"
|
||
|
DExit logTopic = "EXIT"
|
||
|
DPing logTopic = "PING"
|
||
|
DScan logTopic = "SCAN"
|
||
|
DSpawn logTopic = "SPWN"
|
||
|
DStop logTopic = "STOP"
|
||
|
)
|
||
|
|
||
|
// the list can grow
|
||
|
|
||
|
var debugStart time.Time
|
||
|
var debugVerbosity int
|
||
|
|
||
|
func init() {
|
||
|
|
||
|
debugVerbosity = getVerbosity()
|
||
|
debugStart = time.Now()
|
||
|
if debugVerbosity > 0 {
|
||
|
path := "log/"
|
||
|
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
|
||
|
err := os.Mkdir(path, os.ModePerm)
|
||
|
if err != nil {
|
||
|
fmt.Println(err)
|
||
|
os.Exit(1)
|
||
|
}
|
||
|
}
|
||
|
logtype := getLogType() // start with "REACTOR" etc
|
||
|
timestamp := time.Now().Format("Mon-15:04:05")
|
||
|
filename := fmt.Sprintf("%s-%s.log", logtype, timestamp)
|
||
|
f, err := os.OpenFile(path+filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
log.SetOutput(f)
|
||
|
}
|
||
|
|
||
|
log.SetFlags(log.Flags() &^ (log.Ldate | log.Ltime)) // turns off date and time so we can set manually
|
||
|
}
|
||
|
|
||
|
// example call Debug(dClient, "R%d connecting to client %d", r.Id, c.Id)
|
||
|
func Debug(topic logTopic, format string, a ...interface{}) {
|
||
|
if debugVerbosity >= 1 {
|
||
|
time := time.Since(debugStart).Microseconds()
|
||
|
time /= 100
|
||
|
prefix := fmt.Sprintf("%06d %v ", time, string(topic))
|
||
|
format = prefix + format
|
||
|
log.Printf(format, a...)
|
||
|
}
|
||
|
}
|