aboutsummaryrefslogtreecommitdiff
path: root/middleware/log/log.go
blob: 3c941849b2aafa58d7a90913b0143a49624ef68a (plain) (blame)
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
// Package log implements basic but useful request (access) logging middleware.
package log

import (
	"log"
	"time"

	"github.com/miekg/coredns/middleware"
	"github.com/miekg/coredns/middleware/metrics"
	"github.com/miekg/coredns/middleware/pkg/dnsrecorder"
	"github.com/miekg/coredns/middleware/pkg/rcode"
	"github.com/miekg/coredns/middleware/pkg/replacer"
	"github.com/miekg/coredns/request"

	"github.com/miekg/dns"
	"golang.org/x/net/context"
)

// 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) {
	state := request.Request{W: w, Req: r}
	for _, rule := range l.Rules {
		if middleware.Name(rule.NameScope).Matches(state.Name()) {
			responseRecorder := dnsrecorder.New(w)
			rc, err := l.Next.ServeDNS(ctx, responseRecorder, r)

			if rc > 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, rc)
				} else {
					answer := new(dns.Msg)
					answer.SetRcode(r, rc)
					state.SizeAndDo(answer)

					metrics.Report(state, metrics.Dropped, rcode.ToString(rc), answer.Len(), time.Now())
					w.WriteMsg(answer)
				}
				rc = 0
			}
			rep := replacer.New(r, responseRecorder, CommonLogEmptyValue)
			rule.Log.Println(rep.Replace(rule.Format))
			return rc, err

		}
	}
	return l.Next.ServeDNS(ctx, w, r)
}

// Rule configures the logging middleware.
type Rule struct {
	NameScope  string
	OutputFile string
	Format     string
	Log        *log.Logger
}

const (
	// DefaultLogFilename is the default log filename.
	DefaultLogFilename = "query.log"
	// CommonLogFormat is the common log format.
	CommonLogFormat = `{remote} ` + CommonLogEmptyValue + ` [{when}] "{type} {class} {name} {proto} {>do} {>bufsize}" {rcode} {size} {duration}`
	// CommonLogEmptyValue is the common empty log value.
	CommonLogEmptyValue = "-"
	// CombinedLogFormat is the combined log format.
	CombinedLogFormat = CommonLogFormat + ` "{>opcode}"`
	// DefaultLogFormat is the default log format.
	DefaultLogFormat = CommonLogFormat
)