File: file.go

package info (click to toggle)
golang-github-kisom-goutils 0.0~git20161101.0.858c9cb-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 384 kB
  • ctags: 331
  • sloc: makefile: 6
file content (73 lines) | stat: -rw-r--r-- 1,486 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package logging

import "os"

// File writes its logs to file.
type File struct {
	fo, fe *os.File
	*LogWriter
}

func (fl *File) Close() {
	fl.fo.Close()
	if fl.fe != nil {
		fl.fe.Close()
	}
}

// NewFile creates a new Logger that writes all logs to the file
// specified by path. If overwrite is specified, the log file will be
// truncated before writing. Otherwise, the log file will be appended
// to.
func NewFile(path string, overwrite bool) (*File, error) {
	fl := new(File)

	var err error

	if overwrite {
		fl.fo, err = os.Create(path)
	} else {
		fl.fo, err = os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0644)
	}

	if err != nil {
		return nil, err
	}

	fl.LogWriter = NewLogWriter(fl.fo, fl.fo)
	return fl, nil
}

// NewSplitFile creates a new Logger that writes debug and information
// messages to the output file, and warning and higher messages to the
// error file. If overwrite is specified, the log files will be
// truncated before writing.
func NewSplitFile(outpath, errpath string, overwrite bool) (*File, error) {
	fl := new(File)

	var err error

	if overwrite {
		fl.fo, err = os.Create(outpath)
	} else {
		fl.fo, err = os.OpenFile(outpath, os.O_WRONLY|os.O_APPEND, 0644)
	}

	if err != nil {
		return nil, err
	}

	if overwrite {
		fl.fe, err = os.Create(errpath)
	} else {
		fl.fe, err = os.OpenFile(errpath, os.O_WRONLY|os.O_APPEND, 0644)
	}

	if err != nil {
		fl.Close()
		return nil, err
	}

	fl.LogWriter = NewLogWriter(fl.fo, fl.fe)
	return fl, nil
}