Thank you, missed that, didn't fully understand the nature of *defer*, but
now I do!
On Monday, February 5, 2018 at 3:42:10 PM UTC-6, Thomas Bushnell, BSG wrote:
>
> Your init is closing the file before returning, so at that point all the
> writes are failing. If you check the error you receive from logger.Print
> you should see something to that effect.
>
> Thomas
>
>
> On Mon, Feb 5, 2018 at 1:39 PM wrote:
>
>> I'm initializing a Logger variable in an init() function and then
>> attempting to use in the main() function. However, I'm able to Printf from
>> the Logger in the init() function but not inside the main() function. Any
>> help would be appreciated.
>>
>> package main
>>
>> import (
>>
>> "fmt"
>> "log"
>> "io"
>>
>> "os"
>>
>> }
>>
>> var (
>>
>> logFile *os.File
>> logger *log.Logger
>> multiWriter io.Writer
>>
>> )
>>
>> func init() {
>>
>> fmt.Println("init() function")
>>
>> var logFileError error
>> logFile, logFileError = os.Create("gopoc.log")
>> if logFileError != nil {
>> panic(logFileError)
>> }
>> defer logFile.Close()
>>
>> fmt.Println("Creating log file")
>>
>> multiWriter = io.MultiWriter(logFile, os.Stdout)
>>
>> logger = log.New(multiWriter, gopocLogPrefix, log.Ldate | log.Ltime |
>> log.Lshortfile)
>> logger.SetOutput(multiWriter)
>>
>> fmt.Println("Created logger")
>>
>> logger.Printf("Using logger") // prints to console and logFile as
>> expected
>>
>> }
>>
>> func main() {
>>
>> fmt.Println("main() function ") // prints to console
>>
>> fmt.Println(logger) // I can see the object pointer
>>
>> logger.Print("hello") // This does not print to logFile nor
>> os.Stdout !!!
>>
>> }
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to golang-nuts...@googlegroups.com .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.