Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write logs to multiple log files in golang?

Tags:

logging

go

I am writing an application in which i need to record logs in two different files. For Example weblogs.go and debuglogs.go. I tried using the log4go but my requirement is i need the logger to be created in main file and be accessible in sub directory as major of decoding and logging is done in sub file. Can anybody please help with that?

like image 294
Madhuri Desai Avatar asked Feb 22 '19 05:02

Madhuri Desai


Video Answer


1 Answers

Here's one way to do it, using the standard log package:

package main

import (
    "io"
    "log"
    "os"
)

func main() {
    f1, err := os.Create("/tmp/file1")
    if err != nil {
        panic(err)
    }
    defer f1.Close()

    f2, err := os.Create("/tmp/file2")
    if err != nil {
        panic(err)
    }
    defer f2.Close()

    w := io.MultiWriter(os.Stdout, f1, f2)
    logger := log.New(w, "logger", log.LstdFlags)

    myfunc(logger)
}

func myfunc(logger *log.Logger) {
    logger.Print("Hello, log file!!")
}

Notes:

  1. io.MultiWriter is used to combine several writers together. Here, it creates a writer w - a write to w will go to os.Stdout as well as two files
  2. log.New lets us create a new log.Logger object with a custom writer
  3. The log.Logger object can be passed around to functions and used by them to log things
like image 186
Eli Bendersky Avatar answered Oct 09 '22 13:10

Eli Bendersky