made use of string builder in logger

This commit is contained in:
0xdcarns
2022-02-10 11:07:21 -05:00
parent d42ec811b8
commit c238cf7f23
6 changed files with 53 additions and 35 deletions

View File

@@ -125,7 +125,7 @@ func getExtClientConf(w http.ResponseWriter, r *http.Request) {
gwnode, err := logic.GetNodeByID(client.IngressGatewayID) gwnode, err := logic.GetNodeByID(client.IngressGatewayID)
if err != nil { if err != nil {
logger.Log(1, fmt.Sprintf("%s %s %s", r.Header.Get("user"), "Could not retrieve Ingress Gateway Node", client.IngressGatewayID)) logger.Log(1, r.Header.Get("user"), "Could not retrieve Ingress Gateway Node", client.IngressGatewayID)
returnErrorResponse(w, r, formatError(err, "internal")) returnErrorResponse(w, r, formatError(err, "internal"))
return return
} }

View File

@@ -4,44 +4,26 @@ import (
"fmt" "fmt"
"os" "os"
"sort" "sort"
"strconv"
"strings"
"sync" "sync"
"time" "time"
) )
// TimeFormatDay - format of the day for timestamps
const TimeFormatDay = "2006-01-02" const TimeFormatDay = "2006-01-02"
// TimeFormat - total time format
const TimeFormat = "2006-01-02 15:04:05" const TimeFormat = "2006-01-02 15:04:05"
// == fields ==
var currentLogs = make(map[string]string) var currentLogs = make(map[string]string)
var mu sync.Mutex
func makeString(message ...string) string {
return strings.Join(message, " ")
}
func getVerbose() int32 {
level, err := strconv.Atoi(os.Getenv("VERBOSITY"))
if err != nil || level < 0 {
level = 0
}
if level > 3 {
level = 3
}
return int32(level)
}
// ResetLogs - reallocates logs map
func ResetLogs() {
currentLogs = make(map[string]string)
}
// Log - handles adding logs // Log - handles adding logs
func Log(verbosity int, message ...string) { func Log(verbosity int, message ...string) {
var mu sync.Mutex
mu.Lock() mu.Lock()
defer mu.Unlock() defer mu.Unlock()
var currentTime = time.Now() var currentTime = time.Now()
var currentMessage = makeString(message...) var currentMessage = MakeString(" ", message...)
if int32(verbosity) <= getVerbose() && getVerbose() >= 0 { if int32(verbosity) <= getVerbose() && getVerbose() >= 0 {
fmt.Printf("[netmaker] %s %s \n", currentTime.Format(TimeFormat), currentMessage) fmt.Printf("[netmaker] %s %s \n", currentTime.Format(TimeFormat), currentMessage)
} }
@@ -74,9 +56,10 @@ func Dump() string {
for i := range dumpLogs { for i := range dumpLogs {
var currLog = dumpLogs[i] var currLog = dumpLogs[i]
dumpString += fmt.Sprintf("[netmaker] %s %s \n", currLog.Value.Format(TimeFormat), currLog.Key) dumpString += MakeString(" ", "[netmaker]", currLog.Value.Format(TimeFormat), currLog.Key, "\n")
} }
resetLogs()
return dumpString return dumpString
} }
@@ -84,13 +67,14 @@ func Dump() string {
func DumpFile(filePath string) { func DumpFile(filePath string) {
f, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) f, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil { if err != nil {
panic(err) fmt.Println(MakeString("could not open log file", filePath))
return
} }
defer f.Close() defer f.Close()
if _, err = f.WriteString(Dump()); err != nil { if _, err = f.WriteString(Dump()); err != nil {
panic(err) fmt.Println("could not dump logs")
} }
} }
@@ -108,6 +92,13 @@ func FatalLog(message ...string) {
var mu sync.Mutex var mu sync.Mutex
mu.Lock() mu.Lock()
defer mu.Unlock() defer mu.Unlock()
fmt.Printf("[netmaker] Fatal: %s \n", makeString(message...)) fmt.Printf("[netmaker] Fatal: %s \n", MakeString(" ", message...))
os.Exit(2) os.Exit(2)
} }
// == private ==
// resetLogs - reallocates logs map
func resetLogs() {
currentLogs = make(map[string]string)
}

30
logger/util.go Normal file
View File

@@ -0,0 +1,30 @@
package logger
import (
"os"
"strconv"
"strings"
)
// MakeString - makes a string using golang string builder
func MakeString(delimeter string, message ...string) string {
var builder strings.Builder
for i := 0; i < len(message); i++ {
builder.WriteString(message[i])
if delimeter != "" && i != len(message)-1 {
builder.WriteString(delimeter)
}
}
return builder.String()
}
func getVerbose() int32 {
level, err := strconv.Atoi(os.Getenv("VERBOSITY"))
if err != nil || level < 0 {
level = 0
}
if level > 3 {
level = 3
}
return int32(level)
}

View File

@@ -187,7 +187,7 @@ func runGRPC(wg *sync.WaitGroup) {
// Should we be using a context vice a waitgroup???????????? // Should we be using a context vice a waitgroup????????????
func runMessageQueue(wg *sync.WaitGroup) { func runMessageQueue(wg *sync.WaitGroup) {
defer wg.Done() defer wg.Done()
logger.Log(0, fmt.Sprintf("connecting to mq broker at %s", servercfg.GetMessageQueueEndpoint())) logger.Log(0, "connecting to mq broker at", servercfg.GetMessageQueueEndpoint())
var client = mq.SetupMQTT(false) // Set up the subscription listener var client = mq.SetupMQTT(false) // Set up the subscription listener
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
go mq.Keepalive(ctx) go mq.Keepalive(ctx)

View File

@@ -129,7 +129,7 @@ func PublishPeerUpdate(newNode *models.Node) error {
if err = publish(&node, fmt.Sprintf("peers/%s/%s", node.Network, node.ID), data); err != nil { if err = publish(&node, fmt.Sprintf("peers/%s/%s", node.Network, node.ID), data); err != nil {
logger.Log(1, "failed to publish peer update for node", node.ID) logger.Log(1, "failed to publish peer update for node", node.ID)
} else { } else {
logger.Log(1, fmt.Sprintf("sent peer update for node %s on network: %s ", node.Name, node.Network)) logger.Log(1, "sent peer update for node", node.Name, "on network:", node.Network)
} }
} }
return nil return nil

View File

@@ -2,7 +2,6 @@ package serverctl
import ( import (
"errors" "errors"
"fmt"
"net" "net"
"os" "os"
"strings" "strings"
@@ -34,9 +33,7 @@ func InitServerNetclient() error {
var currentServerNode, nodeErr = logic.GetNetworkServerLocal(network.NetID) var currentServerNode, nodeErr = logic.GetNetworkServerLocal(network.NetID)
if nodeErr == nil { if nodeErr == nil {
if err = logic.ServerPull(&currentServerNode, true); err != nil { if err = logic.ServerPull(&currentServerNode, true); err != nil {
logger.Log(1, fmt.Sprintf("failed pull for network %s, on server node %s", logger.Log(1, "failed pull for network", network.NetID, ", on server node", currentServerNode.ID)
network.NetID,
currentServerNode.ID))
} }
} }
} }