Add Line Numbers to Log Output

· 77 words · 1 minute read

Many programming languages allow you to print the line number of when and where something has happened. This is very useful for debugging a problem when it has occurred. By default in Go this is off, but you can turn it on when logging by setting flags.

package main

import "log"

func main() {

    // Enable line numbers in logging
    log.SetFlags(log.LstdFlags | log.Lshortfile)

    // Will print: "[date] [time] [filename]:[line]: [text]"
    log.Println("Logging w/ line numbers on golangcode.com")
}

logging in golang with line numbers

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!