ameshkov / dnslookup

Simple command line utility to make DNS lookups to the specified server
MIT License
816 stars 72 forks source link

Elapsed time in JSON output #61

Closed mohshami closed 7 months ago

mohshami commented 7 months ago

First I would love to say thank you for this wonderful tool. I use it all the time.

One thing I use it for is to do health checks on our caching resolvers, and something I wanted to do was to monitor how long those queries took. But noticed ElapsedTime is only available in the human readable output.

Please forgive me as the last meaningful Go that I wrote was in 2018, and even then my Go skills were quite limited.

My first instinct was to modify the output string slice before printing as follows

var elapsed = fmt.Sprintf(",\n  \"ElapsedTime\": %f \n}", float64(time.Now().Sub(startTime)) / float64(time.Millisecond))
b = append(b[:len(b)-2], elapsed...)

But I didn't feel comfortable editing formatted JSON, because it could conflict with future changes. So I went with the sjson package as follows

import "github.com/tidwall/sjson"

c, err := sjson.Set(string(b), "ElapsedTime", float64(endTime.Sub(startTime)) / float64(time.Millisecond))
if err != nil {
    log.Fatalf("Cannot append elapsed time: %s", err)
}

if err := json.Indent(&prettyJSON, []byte(c), "", "  "); err != nil {
    log.Fatalf("Cannot pretty print reply: %s", err)
}

os.Stdout.WriteString(prettyJSON.String() + "\n")

After that I ended up dropping the sjson requirement, editing compact JSON directly and then formatting the JSON output.

Also, one thing I wanted to monitor was plain DNS-over-TCP, which my script used dig for since I didn't know it was supported by dnslookup. But when when I saw https://pkg.go.dev/github.com/AdguardTeam/dnsproxy/upstream#AddressToUpstream I realized it was possible and after testing it does indeed work. So I thought it would be a good idea to expose it in the README

ameshkov commented 7 months ago

I got the idea and it does make sense, but I'd suggest implement it differently.

Make a new struct, something like this:

type JSONMsg struct {
    Query   *dns.Msg      `json:"query"`
    Message *dns.Msg      `json:"response"`
    Elapsed time.Duration `json:"elapsed"`
}

Fill it with the necessary information and serialize to JSON.

It won't be backwards-compatible, but it will be pretty :)

mohshami commented 7 months ago

Thank you so much.

Yeah my golang-fu isn't any good :)

While working the change you requested I thought of looking at the upstream code and I had an idea, the updated code now uses a struct like you mentioned but is also backwards compatible.

Thanks again :)

ameshkov commented 7 months ago

Please check out the linter warnings and once they're fixed it'll be good to merge.

mohshami commented 7 months ago

Thank you so much, JSONMsg renamed to jsonMsg so it's unexported