How to enable line numbers for log, but only for errors?

I see that log.SetFlags(log.LstdFlags | log.Lshortfile) enables line numbers for all log output. But is there a way to enable line numbers just for error objects, Fatal, and Fatalf?

There is not any way to enable line numbers just for Fatal and Fatalf funcs. However, you can use struct embedding to customize it like so:

package main

import (

type MyLog struct {
	fatal *log.Logger

func New(out io.Writer, prefix string, flag int) *MyLog {
	l := &MyLog{
		Logger: log.New(out, prefix, flag),
		fatal:  log.New(out, prefix, flag|log.LstdFlags|log.Lshortfile),
	return l

func (l *MyLog) Fatal(v ...interface{}) {

func main() {
	logger := New(os.Stderr, "logger: ", log.Lshortfile)

	logger.Print("Hello, log file!")
	logger.Fatal("Hello, log file!")

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.