Parse log lines into Go structs with a format string, without regular expressions. Lines with string, number, UTC time and netip.Addr fields parse with zero allocations; an IPv6 zone new to the process, as in fe80::1%eth9, can allocate.
Give the parser a format string, a line and the struct to fill.
go get github.com/awskii/hunkee
You can specify raw field, which will be filled with raw value (string) of token. Simple:
type s struct {
ID int64 `hunk:"id"`
IDRaw string `hunk:"id_raw"`
}For that example format string might be as simple as ":id".
You can use raw values to parse not supported types.
Note that dots in tags are not supported. Embedded structs are not supported too.
- int, int8, int16, int32, int64
- uint, uint8, uint16, uint32, uint64
- float32, float64
- bool
- string
- time.Time (with layout and timezone parsing)
- time.Duration (a Go duration such as
1.5s, or integer nanoseconds) - net.IP
- netip.Addr (an empty token gives the zero
Addr,-leaves the field unchanged, and an address that does not parse is an error) - url.URL, *url.URL
Example:
// define your structure with needed field. Notice that you can set *_raw fields, which will be
// filled by raw value
var s struct {
ParsedAtTimestamp time.Time `hunk:"date"`
RemoteUser string `hunk:"remote_user"`
RemoteIP netip.Addr `hunk:"remote_addr"`
RemoteIPRaw string `hunk:"remote_addr_raw"`
GeoIPCountryCode string `hunk:"geoip_country_code"`
GeoIPCity string `hunk:"geoip_city"`
GcdnTimetamp time.Time `hunk:"time_local"`
GcdnResponderName string `hunk:"responder_name"`
GcdnAPIClientID uint64 `hunk:"gcdn_api_client_id"`
GcdnResourceID int64 `hunk:"gcdn_api_resource_id"`
RQHeaderHost string `hunk:"host"`
RQHeaderUserAgent string `hunk:"http_user_agent"`
RQLength int64 `hunk:"request_length"`
Size uint64 `hunk:"body_bytes_sent"`
HTTPRequestRaw string `hunk:"request"`
HTTPStatus int `hunk:"status"`
HTTPReferer string `hunk:"http_referer"`
HTTPScheme string `hunk:"scheme"`
HTTPRangeRaw string `hunk:"http_range"`
ServerToClientBytesSent uint64 `hunk:"bytes_sent"`
ServerToClientBytesSentRaw string `hunk:"bytes_sent_raw"`
SentHTTPContentSize uint64 `hunk:"sent_http_content_size"`
SentHTTPContentSizeRaw string `hunk:"sent_http_content_size_raw"`
UpstreamResponseTimeRaw string `hunk:"upstream_response_time"`
UpstreamResponseLengthRaw string `hunk:"upstream_response_length"`
CacheStatus string `hunk:"upstream_cache_status"`
ProcessingTime float64 `hunk:"request_time"`
UpstreamIPRaw string `hunk:"upstream_addr"`
UIDCookieGot string `hunk:"uid_got"`
UIDCookieSet string `hunk:"uid_set"`
ShieldUsedRaw string `hunk:"shield_type"`
}
// define format string
f := `:remote_addr - :remote_user :time_local :request :status ` +
`:body_bytes_sent :http_referer :http_user_agent :bytes_sent :sent_http_content_size ` +
`:scheme :host :request_time :upstream_response_time :request_length :http_range ` +
`:responder_name :upstream_cache_status :upstream_response_length :upstream_addr ` +
`:gcdn_api_client_id :gcdn_api_resource_id :uid_got :uid_set :geoip_country_code ` +
`:geoip_city :shield_type`
// log line
l := `"62.149.10.131" "-" "-" "[04/Jan/2018:19:15:39 +0000]" "GET /dino.jpg HTTP/1.1" "200" "207402" "" "saelmon" "207957" "-" "https" "di.gcdn.co" "0.000" "-" "88" "-" "[gn]" "HIT" "-" "-" "777" "1337" "-" "-" "UA" "-" "shield_no"`
// initialize parser
p, err := NewParser(f, &s)
if err != nil {
fmt.Println(err)
}
// set time parsing format for time_local field and say that all tokens separated by '"'
p.SetTokenSeparator('"')
p.SetTimeLayout("time_local", "[02/Jan/2006:15:04:05 -0700]")
// parse line into s
if err = p.ParseLine(l, &s); err != nil {
fmt.Println(err)
}
fmt.Printf("%#v\n", s)Note that all concurrency dispatch is lying on your shoulders.
One line, 2018-07-28T21:10:45Z 17522 Brighton 20 25.6, into a struct with time.Time, uint16, string, uint8 and float32 fields. ParseRE fills the same struct with regexp.FindStringSubmatch and strconv. ParseNginx parses the line from the Usage example: " as the token separator, raw fields, a custom time layout, and the address field as net.IP. ParseNginxAddr is the same with the address field as netip.Addr. Apple M5 Max, Go 1.26.8, -benchtime 500ms, median of 8 runs.
| Benchmark | time/op | B/op | allocs/op |
|---|---|---|---|
| Parse | 103.3 ns | 0 | 0 |
| ParseWithoutTime | 67.0 ns | 0 | 0 |
| ParseRE | 342.6 ns | 192 | 2 |
| ParseREWithoutTime | 266.8 ns | 281 | 6 |
| ParseNginx | 467.0 ns | 16 | 1 |
| ParseNginxAddr | 463.9 ns | 0 | 0 |
hunkee_bench_test.go and bench_extended_test.go also measure field count, field types, line length and concurrent parsers.
If you pass an unsupported interface or structure, don't open an issue about something going wrong. If you create a structure with a raw field of any type other than string, don't be confused.