git » debian:golang-blitiri-go-log » commit 521063f

Use strings.Builder to construct log line

author Alberto Bertogli
2020-05-22 16:47:42 UTC
committer Alberto Bertogli
2020-05-22 16:55:02 UTC
parent 577ccb2853e60c0d23f1a0a9a69df023cf978f4d

Use strings.Builder to construct log line

Today we construct the log line with string manipulation, and going
backwards, which makes the code harder to read.

This patch changes the code to use a string.Builder and constructs the
line from left to right, which improves readability.

There is a tiny performance benefit too.

log.go +21 -20

diff --git a/log.go b/log.go
index 87bca24..96d84b8 100644
--- a/log.go
+++ b/log.go
@@ -193,20 +193,11 @@ func (l *Logger) Log(level Level, skip int, format string, a ...interface{}) err
 		return nil
 	}
 
-	// Message.
-	msg := fmt.Sprintf(format, a...)
+	b := strings.Builder{}
 
-	// Caller.
-	if l.LogCaller {
-		_, file, line, ok := runtime.Caller(1 + l.callerSkip + skip)
-		if !ok {
-			file = "unknown"
-		}
-		fl := fmt.Sprintf("%s:%-4d", filepath.Base(file), line)
-		if len(fl) > 18 {
-			fl = fl[len(fl)-18:]
-		}
-		msg = fmt.Sprintf("%-18s", fl) + " " + msg
+	// Time.
+	if l.LogTime {
+		b.WriteString(time.Now().Format("2006-01-02 15:04:05.000000 "))
 	}
 
 	// Level.
@@ -215,20 +206,30 @@ func (l *Logger) Log(level Level, skip int, format string, a ...interface{}) err
 		if !ok {
 			letter = strconv.Itoa(int(level))
 		}
-		msg = letter + " " + msg
+		b.WriteString(letter + " ")
 	}
 
-	// Time.
-	if l.LogTime {
-		msg = time.Now().Format("2006-01-02 15:04:05.000000 ") + msg
+	// Caller.
+	if l.LogCaller {
+		_, file, line, ok := runtime.Caller(1 + l.callerSkip + skip)
+		if !ok {
+			file = "unknown"
+		}
+		fl := fmt.Sprintf("%s:%-4d", filepath.Base(file), line)
+		if len(fl) > 18 {
+			fl = fl[len(fl)-18:]
+		}
+		fmt.Fprintf(&b, "%-18s ", fl)
 	}
 
-	if !strings.HasSuffix(msg, "\n") {
-		msg += "\n"
+	// Message.
+	if !strings.HasSuffix(format, "\n") {
+		format += "\n"
 	}
+	fmt.Fprintf(&b, format, a...)
 
 	l.Lock()
-	_, err := l.w.Write([]byte(msg))
+	_, err := l.w.Write([]byte(b.String()))
 	l.Unlock()
 	return err
 }