-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcsvFormatter.go
51 lines (45 loc) · 1.08 KB
/
csvFormatter.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
package main
import (
"bytes"
"encoding/csv"
"runtime"
"strings"
"github.com/ujiro99/logcatf/logcat"
)
// implements Formatter
type csvFormatter struct {
*defaultFormatter
buf *bytes.Buffer
w *csv.Writer
}
func NewCsvFormatter(format string) Formatter {
buf := new(bytes.Buffer)
writer := csv.NewWriter(buf)
res := &csvFormatter{&defaultFormatter{format: &format}, buf, writer}
if runtime.GOOS == Windows {
res.w.UseCRLF = true
}
return res
}
// Format implements Formatter
// replace %* keywords to real value. use short format.
// ex) "%t %a" => "12-28 19:01:14.073", GLSUser
func (f *csvFormatter) Format(item *logcat.Entry) string {
matches := sformatRegex.FindAllStringSubmatch(*f.format, len(formatMap))
args := make([]string, 0, len(matches))
// find matched keyword and store value on item
for _, match := range matches {
for _, m := range match {
key, ok := findKey(formatMap, m)
if ok {
args = append(args, (*item)[key])
break
}
}
}
f.w.Write(args)
f.w.Flush()
res := strings.TrimRight(f.buf.String(), "\r\n")
f.buf.Reset()
return res
}