-
Notifications
You must be signed in to change notification settings - Fork 0
/
pattlog.go
115 lines (97 loc) · 2.51 KB
/
pattlog.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
// Copyright (C) 2010, Kyle Lemons <[email protected]>. All rights reserved.
package log4go
import (
"os"
"strings"
"container/vector"
)
const (
// Only allow these three outputs, so make an enum
STDIN = iota
STDOUT
STDERR
)
const (
FORMAT_DEFAULT = "[%D %T] [%L] (%S) %M"
FORMAT_SHORT = "[%t %d] [%L] %M"
FORMAT_ABBREV = "[%L] %M"
)
// Known format codes:
// %T - Time (15:04:05 MST)
// %t - Time (15:04)
// %D - Date (2006/01/02)
// %d - Date (01/02/06)
// %L - Level (FNST, FINE, DEBG, TRAC, WARN, EROR, CRIT)
// %S - Source
// %M - Message
// Ignores unknown formats
// Recommended: "[%D %T] [%L] (%S) %M"
func FormatLogRecord(format string, rec *LogRecord) string {
var ovec vector.StringVector
// Split the string into pieces by % signs
pieces := strings.Split(format, "%", -1)
ovec.Resize(0, 2*len(pieces)+2) // allocate enough pieces for each piece and its previous plus an extra for the first and last piece for good measure
// Iterate over the pieces, replacing known formats
for i, piece := range pieces {
if i > 0 && len(piece) > 0 {
switch piece[0] {
case 'T':
ovec.Push(rec.Created.Format("15:04:05 MST"))
case 't':
ovec.Push(rec.Created.Format("15:04"))
case 'D':
ovec.Push(rec.Created.Format("2006/01/02"))
case 'd':
ovec.Push(rec.Created.Format("01/02/06"))
case 'L':
ovec.Push(levelStrings[rec.Level])
case 'S':
ovec.Push(rec.Source)
case 'M':
ovec.Push(rec.Message)
}
if len(piece) > 1 {
ovec.Push(piece[1:])
}
} else if len(piece) > 0 {
ovec.Push(piece)
}
}
return strings.Join(ovec, "")+"\n"
}
// This log writer sends output to a file
type FormatLogWriter struct {
// The logging format
format string
// The output file (stdin, stdout, stderr)
out *os.File
}
// This is the FormatLogWriter's output method
func (flw *FormatLogWriter) LogWrite(rec *LogRecord) (n int, err os.Error) {
// Perform the write
return flw.out.Write([]byte(FormatLogRecord(flw.format, rec)))
}
func (flw *FormatLogWriter) Good() bool {
return true
}
func (flw *FormatLogWriter) Close() { }
func NewFormatLogWriter(file int, format string) *FormatLogWriter {
flw := new(FormatLogWriter)
flw.format = format
switch file {
case STDIN:
flw.out = os.Stdin
case STDOUT:
flw.out = os.Stdout
case STDERR:
flw.out = os.Stderr
default:
flw.out = os.Stdin
}
return flw
}
// Set the logging format
func (flw *FormatLogWriter) SetFormat(format string) {
//fmt.Fprintf(os.Stderr, "FormatLogWriter.SetFormat: %v\n", format)
flw.format = format
}