log printf and Write connection

I cannot for the life of me from below golang code, why when you call write function at the bottom,

func write(message string) {
    log.Printf("%v\n", message)
}

why log.Printf calls below method

func (fl fileLog) Write(data []byte) (int, error ) {
    fmt.Println("does this ever get called?")
    f, err := os.OpenFile(string(fl), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
    if err != nil {
        return 0, err
    }

    defer f.Close()
    return f.Write(data)
}

Logger’s printf definition is below

 func (*Logger) Printf ¶

func (l *Logger) Printf(format string, v ...interface{})

— Full Code below, someone please explain to me why this is so please–

package main

import (
    "fmt"
    stlog "log"
    "os"
)

var log *stlog.Logger

type fileLog string

func (fl fileLog) Write(data []byte) (int, error ) {
    fmt.Println("does this ever get called?")
    f, err := os.OpenFile(string(fl), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
    if err != nil {
        return 0, err
    }

    defer f.Close()
    return f.Write(data)
}

func registerHandlers() {
    var msgRaw = "how are you"
    write(msgRaw)
}

func run(destination string) {
    log =  stlog.New(fileLog(destination), "", stlog.LstdFlags)
}

func main() {
    fmt.Println("here we go")
    run("../test.log")
    registerHandlers()
}

func write(message string) {
    log.Printf("%v\n", message)
}

>Solution :

The logger writes the log messages to an io.Writer, which is an interface defined as:

type Writer interface {
   Write([]byte) (int,error)
}

The fileLog type implements the io.Writer interface, and you set it as the output of the new logger. So whenever the logger tries to write a log, it calls the Write function of its writer, which is fileLog.Write.

Leave a Reply