Ankur Tiwari
Ankur Tiwari

Reputation: 125

Not able to write all the log statement to the file

I am trying to create log file for my code. But I am not able to write all the log statement to the file.

Here's my code:

func MyLogger() {
    f, err := os.OpenFile("C:\\Project\\GoLang\\src\\Logs\\LogOutput\\TestLog.log", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
    if err != nil {
        log.Fatalf("error opening file: %v", err)
    }
    defer f.Close()
    log.SetOutput(f)
    log.Println("This is a test log entry")
}

Upvotes: 2

Views: 687

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79734

The problem is that you're closing the log file immediately after opening it.

You're calling log.SetOutput(logFile), but you also call defer logFile.Close(). The defer is executed as soon as the function MyLogger() exits--so before you have any chance to actually log anything.

If your logger will run for the entire duration of the program, you probably don't need to close it at all, and let it just get auto-closed when the program exits.

If you do need to close it before the program exits, you'll need to come up with some way to store that file handle outside of the MyLogger() method (perhaps in a global variable, although there are other options), then close it at the appropriate time.

A complete example:

package Controllers

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

var logCloser io.Closer

func MyLogger() {
    logFile, err := os.OpenFile("C:/Project/GoLang/src/Logs/log.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
    if err != nil {
        panic(err)
    }
    logCloser = logFile
    log.SetOutput(logFile)
}

func CloseMyLogger() {
    logCloser.Close()
}

Upvotes: 5

Related Questions