package logging import ( "log" "fmt" "os" "errors" "time" "strconv" ) 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 Vverboity %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" ) // 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) } } filename := time.Now().Format("01-02T15:04:05") filename += ".log" 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...) } }