Home > Software design >  How to align columns in Golang logger?
How to align columns in Golang logger?

Time:11-04

When configuring Golang logger to show the location in code (like the snippet in the doc), the messages are not aligned.

For example:

$ go run .
main.go:11: From main
afilewithalongname.go:4: From function

How to vertically align the messages "From main" and "From function"?

Below, the MCVE.

File main.go:

package main

import(
        "log"
        "os"
)

var logger = log.New(os.Stderr, "", log.Lshortfile)

func main() {
        logger.Println("From main")
        SomeFunction()
}

File afilewithalongname.go:

package main

func SomeFunction() {
        logger.Println("From function")
}

File go.mod:

module testlog

go 1.17

CodePudding user response:

You don't have that much control over the standard log package. If you simply want to write to stdout you can use fmt.Printf which allows you to pad parts of your string. You can get the file name of the calling function with the runtime.Caller function. To get something like:

func log(msg string) {
    _, file, no, ok := runtime.Caller(1)
    if ok {
        fmt.Printf("0s:%d: %s\n", file, no, msg)
    }
}

The 0s part means we will pad the string to 30 chars wide, this value will depend on your max file size.

I can also recommend a dedicated logging library like logrus which offers you more flexibility in the way our logs are formatted and where they are written to ect.

CodePudding user response:

While the log package in the standard library has some flags such as Ldate and Lshortfile, there is no option to affect the vertical alignment when printed to a console or file.

You would need to choose a logger from outside of the standard library. The default configuration of logrus will perform some vertical alignment when the output device is a TTY.

  • Related