file.go 901 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package logger
  5. import (
  6. "os"
  7. )
  8. // File is a file writer used for logging.
  9. type File struct {
  10. writer *os.File
  11. }
  12. // NewFile creates and returns a pointer to a new File object along with any error that occurred.
  13. func NewFile(filename string) (*File, error) {
  14. file, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
  15. if err != nil {
  16. return nil, err
  17. }
  18. return &File{file}, nil
  19. }
  20. // Write writes the provided logger event to the file.
  21. func (f *File) Write(event *Event) {
  22. f.writer.Write([]byte(event.fmsg))
  23. }
  24. // Close closes the file.
  25. func (f *File) Close() {
  26. f.writer.Close()
  27. f.writer = nil
  28. }
  29. // Sync commits the current contents of the file to stable storage.
  30. func (f *File) Sync() {
  31. f.writer.Sync()
  32. }