Struggling to set up logging to stdout and logfile simultaneously [duplicate]

I’m new to setting up logging from scratch and im not aware of the best practices to do so in go. I’m using the charmbracelet/log library and this is how I’m setting up the logger in the main.go using the init function

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>func init() {
log.SetReportCaller(true)
log.SetReportTimestamp(true)
log.SetTimeFormat(time.Kitchen)
log.SetPrefix("Ares")
log.SetLevel(log.DebugLevel) // TODO : make configurable
log.SetFormatter(log.TextFormatter) // TODO : make configurable
}
</code>
<code>func init() { log.SetReportCaller(true) log.SetReportTimestamp(true) log.SetTimeFormat(time.Kitchen) log.SetPrefix("Ares") log.SetLevel(log.DebugLevel) // TODO : make configurable log.SetFormatter(log.TextFormatter) // TODO : make configurable } </code>
func init() {
    log.SetReportCaller(true)
    log.SetReportTimestamp(true)
    log.SetTimeFormat(time.Kitchen)
    log.SetPrefix("Ares")
    log.SetLevel(log.DebugLevel)        // TODO : make configurable
    log.SetFormatter(log.TextFormatter) // TODO : make configurable
}

With this approach, I’m not sure how to set it up to also spit out a log file when the program shuts down.

I am planning on generating a lot of logs and then use those logs as an excuse to setup elk stack along with Grafana and Prometheus just because I have an excuse to set those up in my project that is going to have multiple microservices some in go and some in python.

I’d really appreciate it if you had some advice on setting up robust logging and observability in general as well.

I did ask this to perplexity and it basically told me to use the io.Multiwriter construct to achieve this https://www.perplexity.ai/search/how-can-i-setup-logging-in-gol-YHG8eEgbTTW1JrGCKSl1.g#0
I was wondering if there is a better way to do this instead of the way given above.

New contributor

theredditbandit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

With this approach, I’m not sure how to set it up to also spit out a log file when the program shuts down.

First, open your output file with os.OpenFile. If successful, you’ll end up with an os.File, which implements io.Writer. os.Stderr also implements io.Writer.

Write to both io.Writers at once with io.MultiWriter.

Finally, you can set that as your log’s output with log.SetOutput.

It might end up looking something like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>package main
import (
"io"
"log"
"os"
"os/exec"
)
func main() {
if f, err := os.OpenFile("/tmp/f", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644); err != nil {
panic(err)
} else {
defer f.Close()
log.SetOutput(io.MultiWriter(f, os.Stderr))
}
for i := 0; i < 3; i++ {
log.Print("Hello World!")
cmd := exec.Command("wc", "/tmp/f")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
panic(err)
}
}
}
</code>
<code>package main import ( "io" "log" "os" "os/exec" ) func main() { if f, err := os.OpenFile("/tmp/f", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644); err != nil { panic(err) } else { defer f.Close() log.SetOutput(io.MultiWriter(f, os.Stderr)) } for i := 0; i < 3; i++ { log.Print("Hello World!") cmd := exec.Command("wc", "/tmp/f") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { panic(err) } } } </code>
package main

import (
    "io"
    "log"
    "os"
    "os/exec"
)

func main() {
    if f, err := os.OpenFile("/tmp/f", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644); err != nil {
        panic(err)
    } else {
        defer f.Close()
        log.SetOutput(io.MultiWriter(f, os.Stderr))
    }
    for i := 0; i < 3; i++ {
        log.Print("Hello World!")
        cmd := exec.Command("wc", "/tmp/f")
        cmd.Stdout = os.Stdout
        cmd.Stderr = os.Stderr
        if err := cmd.Run(); err != nil {
            panic(err)
        }
    }

}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật