forked from odeke-em/drive
/
log.go
117 lines (98 loc) · 2.03 KB
/
log.go
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package log
import (
"fmt"
"io"
"os"
)
type Loggerf func(string, ...interface{}) (int, error)
type Loggerln func(...interface{}) (int, error)
type logy struct {
print Loggerln
printf Loggerf
println Loggerln
}
type logyIn struct {
scan Loggerln
scanf Loggerf
scanln Loggerln
}
type Logger struct {
Logf Loggerf
Logln Loggerln
Log Loggerln
LogErr Loggerln
LogErrf Loggerf
LogErrln Loggerln
Scanf Loggerf
Scan Loggerln
Scanln Loggerln
}
func noopFmter(format string, args ...interface{}) (int, error) {
return 0, nil
}
func nooper(args ...interface{}) (int, error) {
return 0, nil
}
func newLoggerIn(fIn io.Reader) *logyIn {
if fIn == nil {
fIn = os.Stdin
}
finf := func(format string, args ...interface{}) (int, error) {
return fmt.Fscanf(fIn, format, args...)
}
finln := func(args ...interface{}) (int, error) {
return fmt.Fscanln(fIn, args...)
}
fin := func(args ...interface{}) (int, error) {
return fmt.Fscan(fIn, args...)
}
return &logyIn{
scan: fin,
scanf: finf,
scanln: finln,
}
}
func newLoggerOut(f io.Writer) *logy {
ff := nooper
fl := noopFmter
fln := nooper
if f != nil {
fl = func(format string, args ...interface{}) (int, error) {
return fmt.Fprintf(f, format, args...)
}
fln = func(args ...interface{}) (int, error) {
return fmt.Fprintln(f, args...)
}
ff = func(args ...interface{}) (int, error) {
return fmt.Fprint(f, args...)
}
}
return &logy{
print: ff,
printf: fl,
println: fln,
}
}
func New(stdin io.Reader, writers ...io.Writer) *Logger {
var stdout, stderr io.Writer
wLen := len(writers)
if wLen >= 1 {
stdout = writers[0]
}
if wLen >= 2 {
stderr = writers[1]
}
stdouter := newLoggerOut(stdout)
stderrer := newLoggerOut(stderr)
stdiner := newLoggerIn(stdin)
return &Logger{
Logf: stdouter.printf,
Log: stdouter.print,
Logln: stdouter.println,
LogErr: stderrer.print,
LogErrf: stderrer.printf,
LogErrln: stderrer.println,
Scanf: stdiner.scanf,
Scanln: stdiner.scanln,
}
}