Bayu
Bayu

Reputation: 2654

log.SetFlags(log.LstdFlags | log.Lshortfile) in production

Is it good practice (at least general practice) to have log.SetFlags(log.LstdFlags | log.Lshortfile) in production in Go? I wonder if there is whether performance or security issue by doing it in production. Since it is not default setting of log package in Go. Still can't find any official reference or even opinion article regarding that matter.

Upvotes: 4

Views: 6933

Answers (1)

Markus W Mahlberg
Markus W Mahlberg

Reputation: 20712

As for the performance. Yes, it has an impact, however, it is imho negligible for various reasons.

Testing

Code

package main

import (
    "io/ioutil"
    "log"
    "testing"
)

func BenchmarkStdLog(b *testing.B) {
    // We do not want to benchmark the shell
    stdlog := log.New(ioutil.Discard, "", log.LstdFlags)
    for i := 0; i < b.N; i++ {
        stdlog.Println("foo")
    }
}

func BenchmarkShortfile(b *testing.B) {
    slog := log.New(ioutil.Discard, "", log.LstdFlags|log.Lshortfile)
    for i := 0; i < b.N; i++ {
        slog.Println("foo")
    }
}

Result

goos: darwin
goarch: amd64
pkg: stackoverflow.com/go/logbench
BenchmarkStdLog-4        3803840           277 ns/op           4 B/op          1 allocs/op
BenchmarkShortfile-4     1000000          1008 ns/op         224 B/op          3 allocs/op

Your mileage may vary, but the order of magnitude should be roughly equal.

Why I think the impact is negligible

It is unlikely that your logging will be the bottleneck of your application, unless you write a shitload of logs. In 99 times out of 100, it is not the logging which is the bottleneck.

Get your application up and running, load test and profile it. You can still optimize then.

Hint: make sure you can scale out.

Upvotes: 4

Related Questions