# How to write a log format in ABNF and compile it to a rule table

> Write a log line format in RFC 5234 ABNF, compile it to one rule table for the TypeScript and Go tabnas engines, and hold apg-js and peggy to the same verdicts.

Source: https://voxgig.com/howto/abnf-grammar-for-a-log-format

- Audience: platform-team
- Level: beginner
- Languages: typescript, go
- Verified: 2026-11-29
- Published: 2026-11-29

## Short answer

Write the log line in RFC 5234 ABNF and mark every keyword `%s"..."`, because plain ABNF strings match in any case. `@tabnas/abnf` compiles that one file into a rule table that the TypeScript and Go tabnas engines both run, returning a `{rule, src, kids}` tree. Check the result against apg-js and a peggy translation with ten real lines, one of which must fail.

---
## You will need

Node 22 or later, Go 1.24.7 or later for the Go engine, and ten real lines of your format.
Verified 2026-11-29 against Node 22.23.5, Go 1.24.7 and 1.25.14, `@tabnas/abnf` 0.5.1,
`@tabnas/parser` 0.12.21, apg-js 4.4.0, and peggy 5.1.1. The three `@tabnas` packages declare
`node >= 24` in their `engines` field, so `npm ci` under Node 22 prints an `EBADENGINE` warning
and installs them. Every command on this page ran under Node 22.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [`@tabnas/abnf`](https://github.com/tabnas/abnf) | One ABNF file must drive parsers in TypeScript and Go, and the rule table should be inspectable | An engine that asks for Node 24, and a tree that drops rules referenced first in an alternative | One language reads the format, and a debugger matters more than a table |
| [apg-js](https://github.com/ldthomas/apg-js) | JavaScript only, ABNF kept close to the RFC, and lookahead or other SABNF extensions wanted | Core rules defined by hand, and `/` that keeps the first alternative that matches | The grammar lists alternatives in RFC order, or a Go program needs it |
| [peggy](https://peggyjs.org/documentation.html#grammar-syntax-and-semantics-parsing-expression-types) | A JavaScript parser you can step through, and you accept a second grammar file | A hand translation to keep in step with the ABNF, with the opposite default for case | The ABNF file must stay the single source of truth |

Voxgig maintains tabnas. It is one of three options here, not the recommendation.

Of the three, only tabnas compiles the same file in both TypeScript and Go. It charges a tree you have to
learn, because rules referenced at the start of an alternative leave no node. apg-js
reads the same ABNF file plus four core rules, and orders alternatives the way PEG does. peggy
needs a translation by hand, which is a second file that can drift from the first.

## Write the line in RFC 5234 ABNF

A line is a UTC timestamp, a level, `key=value` fields, and optional free text after ` - `.
Each level is written `%s"..."`, the
[RFC 7405](https://www.rfc-editor.org/rfc/rfc7405.html) form for a case-sensitive string.

```text title="log.abnf"
; A log line: a UTC timestamp, a level, key=value fields, and optional
; free text after " - ". RFC 5234 ABNF, with RFC 7405 %s for the levels.
line      = timestamp SP level *(SP item)
item      = field / "-" SP text
timestamp = date "T" time "Z"
date      = 4DIGIT "-" 2DIGIT "-" 2DIGIT
time      = 2DIGIT ":" 2DIGIT ":" 2DIGIT ["." 1*3DIGIT]
level     = %s"DEBUG" / %s"INFO" / %s"WARNING" / %s"WARN" / %s"ERROR"
field     = key "=" value
key       = ALPHA *(ALPHA / DIGIT / "_")
value     = quoted / 1*(%x21 / %x23-3C / %x3E-7E)
quoted    = DQUOTE *(%x20-21 / %x23-7E) DQUOTE
text      = *(%x20-7E)
```

`WARNING` comes before `WARN` on purpose. RFC 5234 gives alternatives no order, but apg-js and
peggy try them in order, and so does tabnas for plain strings, as the failure section shows.

## Compile it to a rule table

`tn.abnf()` compiles the grammar into the engine instance.[^1] Nothing is written to disk. The
`space` option comes first, for a reason the failure section gives.

```ts title="tabnas-log.mjs"
export function makeTabnasParser(grammar = LOG_ABNF, { spaceLex = false } = {}) {
  const tn = new Tabnas({ plugins: [abnf] })
  tn.options({ space: { lex: spaceLex } })
  tn.abnf(grammar)
  return (line) => tn.parse(line)
}
```

The package's `tabnas-abnf` command does the same from a shell and prints the tree for one line.
Every node has the shape the [package README](https://github.com/tabnas/abnf) gives:
`rule`, `src` and `kids`.

```bash
npx tabnas-abnf -f log.abnf --parse '2026-11-29T08:02:44Z ERROR host=db1 - connection refused'
```

```text output
ok: "2026-11-29T08:02:44Z ERROR host=db1 - connection refused" -> {
  "rule": "line",
  "src": "2026-11-29T08:02:44Z ERROR host=db1 - connection refused",
  "kids": [
    {
      "rule": "time",
      "src": "08:02:44",
      "kids": []
    },
    {
      "rule": "level",
      "src": "ERROR",
      "kids": []
    },
```

There is no `timestamp`, `date`, `field` or `key` node. The
[compiler's concepts guide](https://github.com/tabnas/abnf/blob/main/ts/doc/concepts.md) says a
rule referenced at the start of an alternative is inlined and leaves no node, so the key is
read from the `item` node's `src`.

The table itself is data you can list. `--marks` prints each compiled alternative with the token
or rule that opens it, and its `level` lines show the five levels as five fixed tokens:

```bash
npx tabnas-abnf -f log.abnf --marks
```

```text output
level  o:DEBUG  s:#DEBUG
level  o:INFO  s:#INFO
level  o:WARNING  s:#WARNING
level  o:WARN  s:#WARN
level  o:ERROR  s:#ERROR
```

## Run the same file in Go

The Go port, [`github.com/tabnas/abnf/go`](https://pkg.go.dev/github.com/tabnas/abnf/go),
compiles the same file. `main.go` embeds `log.abnf` rather than keeping a copy.

```go title="main.go"
func parseAll(path string) ([]result, error) {
	spec, err := abnf.Abnf(grammar, nil)
	if err != nil {
		return nil, fmt.Errorf("compile: %w", err)
	}
	// The lexer skips spaces and tabs between tokens unless told not to.
	off := false
	j := tabnas.Make(tabnas.Options{Space: &tabnas.SpaceOptions{Lex: &off}})
	j.Grammar(spec)
```

```bash
go run .
```

```text output
 1  accept
 2  accept
 3  accept
 4  accept
 5  accept
 6  accept
 7  accept
 8  accept
 9  accept
10  reject
```

The test runs `go run . trees` as well and compares each Go tree with the TypeScript tree for the
same line, key for key.

## Hold apg-js and peggy to the same verdicts

apg-js reads the same file, with one addition. It defines no core rules, so `ALPHA`, `DIGIT`,
`DQUOTE` and `SP` come from `core.abnf`, four lines copied from
[RFC 5234 Appendix B.1](https://www.rfc-editor.org/rfc/rfc5234.html#appendix-B.1). Without it,
generation stops on `Rule name 'ALPHA' used but not defined`.

```ts title="apg-log.mjs"
export function makeApgParser(grammar = LOG_ABNF) {
  const api = new apgApi(grammar + read('core.abnf'))
  api.generate()
  if (api.errors.length) throw new Error(`apg-js: ${api.errorsToAscii()}`)
  const object = api.toObject()
  const parser = new apgLib.parser()
```

What apg-js generates is a grammar object, one table of opcodes per rule, which the apg-lib parser
walks by recursive descent. peggy generates parser source from `log.peggy`, a hand translation in
which `"ERROR"` is case-sensitive, the opposite of ABNF.

```bash
node verdicts.mjs
```

```text output
    @tabnas/abnf  apg-js        peggy
 1  accept        accept        accept
 2  accept        accept        accept
 3  accept        accept        accept
 4  accept        accept        accept
 5  accept        accept        accept
 6  accept        accept        accept
 7  accept        accept        accept
 8  accept        accept        accept
 9  accept        accept        accept
10  reject        reject        reject
same verdict from all three on every line: true
```

## Check it worked

`log.test.mjs` asserts the ten verdicts for each parser and the Go trees, and pins the pitfalls
below, with the [Node test runner](https://nodejs.org/api/test.html).

```bash
node --test log.test.mjs
```

```text output
1..10
# tests 10
# suites 0
# pass 10
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

Line 10 is `2026-11-29T08:03:10Z error host=db1 - lowercase level`. It is the line that must
fail, and the next section shows why it is the one that matters.

## When it goes wrong

Line 10 parses when the level rule is written `"ERROR"`, because
[RFC 5234 section 2.3](https://www.rfc-editor.org/rfc/rfc5234.html#section-2.3) says ABNF strings
are case-insensitive and `error` matches. A peggy translation of the same rule rejects it, so the
programs disagree.

```bash
node pitfall.mjs
```

```text output
line 10: 2026-11-29T08:03:10Z error host=db1 - lowercase level
  level as plain "ERROR"      @tabnas/abnf accept   apg-js accept
  level as %s"ERROR"          @tabnas/abnf reject   apg-js reject
  level as %x45.52.52.4F.52   @tabnas/abnf reject   apg-js reject
  peggy "ERROR", as log.peggy has it  reject

line 5: 2026-11-29T08:01:18Z WARNING disk=91% mount=/var
  WARN before WARNING, %s strings     @tabnas/abnf accept   apg-js reject
  WARN before WARNING, plain strings  @tabnas/abnf reject
  WARN before WARNING in log.peggy    peggy reject
```

Write each keyword as `%s"ERROR"`, or as the `%x` byte sequence where a tool predates RFC 7405.
Both compilers here accept `%s`, and the test confirms it.

The second block is the order trap. apg-js tries alternatives
[left to right until one matches](https://unpkg.com/apg-js@4.4.0/src/apg-lib/parser.js), so `WARN`
takes the first four letters of `WARNING` and the line fails. tabnas tolerates either order for
`%s` strings, which compile to fixed tokens, and fails for plain strings. List the longer keyword
first and the question never comes up.

The third failure is quiet. With its default options the tabnas lexer skips spaces and tabs
between tokens, as its [options reference](https://github.com/tabnas/parser/blob/main/ts/doc/options.md)
lists under `space`. `log.abnf` names `SP`, so a space still counts, but a tab inside a value is
dropped. `msg="tab<TAB>here"` then parses, with `src` reading `"tabhere"`. Set `space.lex` to `false`,
as both `makeTabnasParser` and `main.go` do, and the tests confirm that both engines refuse the
tab.

## When not to do this

Do not adopt `@tabnas/abnf` for a format that one TypeScript program reads. peggy gives you
generated source you can step through, and the case for tabnas is the second language. Do not
install it on a fleet pinned below Node 24 without testing there first: its packages ask for
Node 24, and this page ran them under Node 22 only.

Do not rely on the tree's shape matching the grammar's. Rules referenced first in an alternative
leave no node, so code that walks the tree depends on how you ordered each rule.

Do not choose apg-js for a grammar copied from an RFC without reordering it, since its first
matching alternative wins. It is the better pick when you want SABNF lookahead and a strict mode
that checks the file against RFC 5234 itself.[^2]

## Related how-tos

- [Parse one config format identically in TypeScript and Go](/howto/parse-one-config-format-in-typescript-and-go)

- [Attach parse actions to grammar rules by name](/howto/attach-parse-actions-by-rule-name)

- [Add a literal to a JSON grammar without forking the parser](/howto/extend-a-json-grammar-with-a-new-literal)

- [Choose between PEG, LALR, and a hand-written parser](/howto/choose-a-parsing-approach-for-your-format)

- [Debug a grammar that rejects valid input](/howto/debug-a-grammar-that-rejects-valid-input)

## Last verified

Verified 2026-11-29 against Node 22.23.5, Go 1.24.7 and 1.25.14, `@tabnas/abnf` 0.5.1,
`@tabnas/parser` 0.12.21, `github.com/tabnas/abnf/go` v0.5.1, `github.com/tabnas/parser/go`
v0.12.21, apg-js 4.4.0, and peggy 5.1.1. Every output block is what the command preceding it
printed. The `@tabnas` packages ran under Node 22, below the Node 24 their `engines` field asks
for.

[^1]: The [tabnas site](https://tabnas.dev/) gives the name a long form and glosses that form as
a table of translations. That is a fair account of what the compiler hands the engine: a table,
and a grammar translated into it.

[^2]: Strict here is stricter than most grammar files. The
[ABNF definition of ABNF](https://www.rfc-editor.org/rfc/rfc5234.html#section-4) ends each rule
with `c-nl`, a comment or CRLF, so a grammar saved with Unix line endings is not strictly ABNF.
apg-js in strict mode refuses `log.abnf` for exactly that reason, line by line, and accepts the
same text once every LF becomes CRLF. `log.test.mjs` checks both.