Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading