R
R
Roman Kharchenko2019-07-31 08:07:43
go
Roman Kharchenko, 2019-07-31 08:07:43

The file is not being written. What is the problem?

Good afternoon.
I'm trying to make friends with journaling, it doesn't work out very well:

import (
"log"
)
/*******************/
type Client struct {
  Logger        *log.Logger
}

ex, _ := os.Executable()
  path := filepath.Dir(ex)
  pathlog := path + string(filepath.Separator) + "log" + string(filepath.Separator)
  if _, err := os.Stat(pathlog); os.IsNotExist(err) {
    _ = os.MkdirAll(pathlog, os.ModePerm)
  }
  f, err := os.OpenFile(pathlog + time.Now().Format("02-01-2006_15-04-05") +".log", os.O_CREATE,0777)
  if err != nil {
    panic(err)
  }
  defer f.Close()

  //f.Sync()

  client.Logger = log.New(bufio.NewWriter(f), version, log.Lshortfile)
  client.Logger.Print("Test text")

The directory is created if it does not exist. The file is being created. BUT! nothing is written to the file.
What is the reason?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Tikhonov, 2019-07-31
@Sarymian

bufio.NewWriter(f)
This thing buffers the write to disk, it must be flashed separately from the file itself. Without this wrapper (New(f, ...)) the entry goes to the log.

P
Papa, 2019-07-31
Stifflera @PapaStifflera

I can assume that this is it: bufio .NewWriter(f).
Either do Flush() or use an unbuffered io.Writer.

w := bufio.NewWriter(f)
defer w.Flush()
client.Logger = log.New(w, version, log.Lshortfile)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question