forked from mackerelio/mackerel-agent-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
accesslog.go
221 lines (207 loc) · 5.42 KB
/
accesslog.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package mpaccesslog
import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/Songmu/axslogparser"
"github.com/Songmu/postailer"
mp "github.com/mackerelio/go-mackerel-plugin"
"github.com/mackerelio/golib/pluginutil"
"github.com/montanaflynn/stats"
)
// AccesslogPlugin mackerel plugin
type AccesslogPlugin struct {
prefix string
file string
posFile string
parser axslogparser.Parser
noPosFile bool
}
// MetricKeyPrefix interface for PluginWithPrefix
func (p *AccesslogPlugin) MetricKeyPrefix() string {
if p.prefix == "" {
p.prefix = "accesslog"
}
return p.prefix
}
// GraphDefinition interface for mackerelplugin
func (p *AccesslogPlugin) GraphDefinition() map[string]mp.Graphs {
labelPrefix := strings.Title(p.prefix)
return map[string]mp.Graphs{
"access_num": {
Label: labelPrefix + " Access Num",
Unit: "integer",
Metrics: []mp.Metrics{
{Name: "total_count", Label: "Total Count"},
{Name: "5xx_count", Label: "HTTP 5xx Count", Stacked: true},
{Name: "4xx_count", Label: "HTTP 4xx Count", Stacked: true},
{Name: "3xx_count", Label: "HTTP 3xx Count", Stacked: true},
{Name: "2xx_count", Label: "HTTP 2xx Count", Stacked: true},
},
},
"access_rate": {
Label: labelPrefix + " Access Rate",
Unit: "percentage",
Metrics: []mp.Metrics{
{Name: "5xx_percentage", Label: "HTTP 5xx Percentage", Stacked: true},
{Name: "4xx_percentage", Label: "HTTP 4xx Percentage", Stacked: true},
{Name: "3xx_percentage", Label: "HTTP 3xx Percentage", Stacked: true},
{Name: "2xx_percentage", Label: "HTTP 2xx Percentage", Stacked: true},
},
},
"latency": {
Label: labelPrefix + " Latency",
Unit: "float",
Metrics: []mp.Metrics{
{Name: "99_percentile", Label: "99 Percentile"},
{Name: "95_percentile", Label: "95 Percentile"},
{Name: "90_percentile", Label: "90 Percentile"},
{Name: "average", Label: "Average"},
},
},
}
}
var posRe = regexp.MustCompile(`^([a-zA-Z]):[/\\]`)
func (p *AccesslogPlugin) getPosPath() string {
base := p.file + ".pos.json"
if p.posFile != "" {
if filepath.IsAbs(p.posFile) {
return p.posFile
}
base = p.posFile
}
return filepath.Join(
pluginutil.PluginWorkDir(),
"mackerel-plugin-accesslog.d",
posRe.ReplaceAllString(base, `$1`+string(filepath.Separator)),
)
}
func (p *AccesslogPlugin) getReadCloser() (io.ReadCloser, bool, error) {
if p.noPosFile {
rc, err := os.Open(p.file)
return rc, true, err
}
posfile := p.getPosPath()
fi, err := os.Stat(posfile)
// don't output count metrics when the pos file doesn't exist or is too old
takeCount := err == nil && fi.ModTime().After(time.Now().Add(-2*time.Minute))
rc, err := postailer.Open(p.file, posfile)
return rc, takeCount, err
}
// FetchMetrics interface for mackerelplugin
func (p *AccesslogPlugin) FetchMetrics() (map[string]float64, error) {
rc, takeCount, err := p.getReadCloser()
if err != nil {
return nil, err
}
defer rc.Close()
countMetrics := []string{"total_count", "2xx_count", "3xx_count", "4xx_count", "5xx_count"}
ret := make(map[string]float64)
for _, k := range countMetrics {
ret[k] = 0
}
var reqtimes []float64
r := bufio.NewReader(rc)
for {
var (
l *axslogparser.Log
err error
bb bytes.Buffer
)
buf, isPrefix, err := r.ReadLine()
bb.Write(buf)
for isPrefix {
buf, isPrefix, err = r.ReadLine()
if err != nil {
break
}
bb.Write(buf)
}
if err != nil {
if err != io.EOF {
log.Println(err)
}
break
}
line := bb.String()
if p.parser == nil {
p.parser, l, err = axslogparser.GuessParser(line)
} else {
l, err = p.parser.Parse(line)
}
if err != nil {
log.Println(err)
continue
}
ret[string(fmt.Sprintf("%d", l.Status)[0])+"xx_count"]++
ret["total_count"]++
if l.ReqTime != nil {
reqtimes = append(reqtimes, *l.ReqTime)
} else if l.TakenSec != nil {
reqtimes = append(reqtimes, *l.TakenSec)
}
}
if ret["total_count"] > 0 {
for _, v := range []string{"2xx", "3xx", "4xx", "5xx"} {
ret[v+"_percentage"] = ret[v+"_count"] * 100 / ret["total_count"]
}
}
if len(reqtimes) > 0 {
ret["average"], _ = stats.Mean(reqtimes)
for _, v := range []int{90, 95, 99} {
ret[fmt.Sprintf("%d", v)+"_percentile"], _ = stats.Percentile(reqtimes, float64(v))
}
}
if !takeCount {
for _, k := range countMetrics {
delete(ret, k)
}
}
return ret, nil
}
// Do the plugin
func Do() {
var (
optPrefix = flag.String("metric-key-prefix", "", "Metric key prefix")
optFormat = flag.String("format", "", "Access Log format ('ltsv' or 'apache')")
optPosFile = flag.String("posfile", "", "(not necessary to specify it in the usual use case) posfile")
optNoPosFile = flag.Bool("no-posfile", false, "no position file")
)
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [OPTION] /path/to/access.log\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
if flag.NArg() < 1 {
flag.Usage()
os.Exit(1)
}
var parser axslogparser.Parser
switch *optFormat {
case "":
parser = nil // guess format by log (default)
case "ltsv":
parser = &axslogparser.LTSV{}
case "apache":
parser = &axslogparser.Apache{}
default:
fmt.Fprintf(os.Stderr, "Error: '%s' is invalid format name\n", *optFormat)
flag.Usage()
os.Exit(1)
}
mp.NewMackerelPlugin(&AccesslogPlugin{
prefix: *optPrefix,
file: flag.Args()[0],
posFile: *optPosFile,
noPosFile: *optNoPosFile,
parser: parser,
}).Run()
}