This repository has been archived by the owner on Jan 4, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
94 lines (85 loc) · 2 KB
/
logger.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
package graphpipe
import (
"fmt"
"io"
"os"
"reflect"
"time"
)
type syncWriter interface {
Sync() error
io.Writer
}
// A universal logger.
// It is not recommended to use this Node in high performance programs,
// as reflection is extensively used.
type Logger struct {
name string
sources []AnySource
output syncWriter
}
type LoggerConfig struct {
Name string
Output string
}
func (l *Logger) Update(mytid int) (result Result) {
fmt.Fprintf(l.output, "%v [%d]%s:", time.Now().Format("0102 15:04:05"), mytid, l.name)
for _, source := range l.sources {
valueMethod := reflect.ValueOf(source).MethodByName("Value")
results := valueMethod.Call([]reflect.Value{})
fmt.Fprintf(l.output, "\t")
for _, r := range results {
fmt.Fprintf(l.output, "[%v]", r.Interface())
}
if source.Closed() {
fmt.Print("!")
}
}
fmt.Fprintln(l.output)
l.output.Sync()
return
}
func (l *Logger) Closed() bool {
for _, s := range l.sources {
if !s.Closed() {
return false
}
}
return true
}
func (l *Logger) SetInput(sources ...AnySource) {
for i, source := range sources {
valueMethod := reflect.ValueOf(source).MethodByName("Value")
if valueMethod.Kind() != reflect.Func {
fmt.Errorf("%d source: Cannot find Value method!", i)
}
if valueMethod.Type().NumIn() != 0 {
fmt.Errorf("%d source: Value method must have 0 inputs!", i)
}
if valueMethod.Type().Out(0).Kind() != reflect.Int {
fmt.Errorf("%d source: Value method must return (int, _)!", i)
}
}
l.sources = sources
}
func newLogger(config *LoggerConfig, sources ...AnySource) (*Logger, error) {
var output syncWriter
switch config.Output {
case "", "-":
output = os.Stdout
case "--":
output = os.Stderr
default:
var err error
output, err = os.OpenFile(config.Output, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return nil, err
}
}
fmt.Fprintln(output, "--------", time.Now())
output.Sync()
return &Logger{name: config.Name, output: output}, nil
}
func init() {
Register("Logger", newLogger)
}