Files
coredns/middleware/log/log.go

76 lines
2.2 KiB
Go
Raw Normal View History

2016-03-18 20:57:35 +00:00
// Package log implements basic but useful request (access) logging middleware.
package log
import (
"log"
"time"
2016-03-18 20:57:35 +00:00
"github.com/miekg/coredns/middleware"
"github.com/miekg/coredns/middleware/metrics"
2016-03-18 20:57:35 +00:00
"github.com/miekg/dns"
"golang.org/x/net/context"
2016-03-18 20:57:35 +00:00
)
// Logger is a basic request logging middleware.
type Logger struct {
Next middleware.Handler
Rules []Rule
ErrorFunc func(dns.ResponseWriter, *dns.Msg, int) // failover error handler
}
func (l Logger) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
2016-03-19 11:16:08 +00:00
state := middleware.State{W: w, Req: r}
2016-03-18 20:57:35 +00:00
for _, rule := range l.Rules {
if middleware.Name(rule.NameScope).Matches(state.Name()) {
2016-03-19 11:16:08 +00:00
responseRecorder := middleware.NewResponseRecorder(w)
rcode, err := l.Next.ServeDNS(ctx, responseRecorder, r)
2016-03-19 11:16:08 +00:00
if rcode > 0 {
// There was an error up the chain, but no response has been written yet.
// The error must be handled here so the log entry will record the response size.
if l.ErrorFunc != nil {
l.ErrorFunc(responseRecorder, r, rcode)
} else {
rc := middleware.RcodeToString(rcode)
2016-03-19 11:16:08 +00:00
answer := new(dns.Msg)
answer.SetRcode(r, rcode)
state.SizeAndDo(answer)
metrics.Report(metrics.Dropped, state.Proto(), rc, answer.Len(), time.Now())
2016-03-19 11:16:08 +00:00
w.WriteMsg(answer)
2016-03-18 20:57:35 +00:00
}
2016-03-19 11:16:08 +00:00
rcode = 0
2016-03-18 20:57:35 +00:00
}
2016-03-19 11:16:08 +00:00
rep := middleware.NewReplacer(r, responseRecorder, CommonLogEmptyValue)
rule.Log.Println(rep.Replace(rule.Format))
return rcode, err
}
2016-03-18 20:57:35 +00:00
}
return l.Next.ServeDNS(ctx, w, r)
2016-03-18 20:57:35 +00:00
}
// Rule configures the logging middleware.
type Rule struct {
2016-03-19 11:16:08 +00:00
NameScope string
2016-03-18 20:57:35 +00:00
OutputFile string
Format string
Log *log.Logger
Roller *middleware.LogRoller
}
const (
// DefaultLogFilename is the default log filename.
2016-03-19 11:16:08 +00:00
DefaultLogFilename = "query.log"
2016-03-18 20:57:35 +00:00
// CommonLogFormat is the common log format.
CommonLogFormat = `{remote} ` + CommonLogEmptyValue + ` [{when}] "{type} {class} {name} {proto} {>do} {>bufsize}" {rcode} {size} {duration}`
2016-03-18 20:57:35 +00:00
// CommonLogEmptyValue is the common empty log value.
CommonLogEmptyValue = "-"
// CombinedLogFormat is the combined log format.
2016-03-19 11:16:08 +00:00
CombinedLogFormat = CommonLogFormat + ` "{>opcode}"`
2016-03-18 20:57:35 +00:00
// DefaultLogFormat is the default log format.
DefaultLogFormat = CommonLogFormat
)