charmbracelet / log

A minimal, colorful Go logging library 🪵
MIT License
2.4k stars 67 forks source link

Toggle ReportCaller on specific log calls #56

Closed Script47 closed 1 year ago

Script47 commented 1 year ago

Is it possible to toggle ReportCaller on Fatal/Fatalf and Error/Errorf calls but not the remaining calls?

JustJordanT commented 1 year ago

I did something like this, making a service for logging and then calling this throughout my project.

package loggy

import (
    "github.com/charmbracelet/log"
    "os"
)

type Logger struct {
    *log.Logger
}

func New() *Logger {
    return &Logger{log.NewWithOptions(os.Stdout, log.Options{
        ReportCaller:    true,
        ReportTimestamp: true,
    })}
}

func (log *Logger) Fatal(args ...interface{}) {
    file, err := os.OpenFile("logfile.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
    if err != nil {
        log.Fatal(err)
    }

    log.SetReportCaller(true)

    log.SetOutput(file)

    log.Fatal(args)
    file.Close().Error()
}

Hope this was helpful.

Script47 commented 1 year ago

@JustJordanT

Definitely helpful, thanks.

I hadn't even considered making a wrapper around it.