archive2022

Full-text search for test logs with Elasticsearch 8

A small Elasticsearch 8 setup in Docker for searching test results, stack traces and long logs across many runs: index design, an analyzer that keeps class names and error codes searchable, bulk indexing from Python, queries, and when PostgreSQL full-text search is enough.

Last month I wrote about grouping test failures by fingerprint with Pandas and PostgreSQL. That answers “which errors do we have and how often”. It does not answer a question we got almost every week at work: “did we see this before?” Usually the person asking had one line from a log or a stack trace, for example a method name or an error code from the portal, and wanted to know in which runs it appeared.

The Azure DevOps test tab can filter by test name, outcome and run. As far as I could find, it cannot search inside the console output of a test, and it does not search across many runs at once. Our Selenium tests write a lot to the console: page names, waits, request ids, the text of error banners. That log is often where the real cause is. So I put the results into Elasticsearch.

This is a setup for a small team, one node, not a production cluster.

Running Elasticsearch 8 in Docker

Elasticsearch 8.0 came out in February 2022, and the big change for a small setup is that security is on by default. The first start creates TLS certificates and a password for the elastic user. I use 8.5.0, the current release when I set this up.

docker network create elastic

docker run -d --name es01 --net elastic -p 9200:9200 \
  -e ES_JAVA_OPTS="-Xms1g -Xmx1g" \
  -v esdata:/usr/share/elasticsearch/data \
  docker.elastic.co/elasticsearch/elasticsearch:8.5.0

# create a new password for the elastic user (it is printed once)
docker exec -it es01 /usr/share/elasticsearch/bin/elasticsearch-reset-password -u elastic

# copy the CA certificate so clients can verify TLS
docker cp es01:/usr/share/elasticsearch/config/certs/http_ca.crt .

curl --cacert http_ca.crt -u elastic https://localhost:9200

On Linux the host also needs vm.max_map_count of at least 262144 (sysctl -w vm.max_map_count=262144, and put it in /etc/sysctl.conf to keep it).

My first attempt was to turn security off with xpack.security.enabled=false, because I only wanted to try things. It works, but then the Python code and the curl commands are different from what you need later. I kept security on from the second day. It is two extra lines in the client.

A 1 GB heap was enough for our volume. I did not need Kibana for this; a small search page and the Python client were enough. If you want Kibana, the enrollment token is printed in the container log on the first start.

One document per test result

Each document is one test result in one run:

Field Type Why
run_id, build_id keyword filter by run or build
test_name keyword + text subfield exact filter and partial search
outcome keyword filter Failed / Passed
fingerprint, exc_type keyword aggregate, join back to PostgreSQL
message, stack_trace, log text full-text search
timestamp date time range, retention

keyword fields are not analyzed. You use them for exact filters, sorting and aggregations. text fields are split into tokens for full-text search. A common mistake is to make outcome a text field and then wonder why a terms aggregation fails.

I put passed tests in the index too. Their logs are useful when you want to compare a good run with a bad one.

An analyzer for code-like text

The default standard analyzer is made for normal language. With stack traces it gave me two problems. It kept OpenQA.Selenium.NoSuchElementException as one token, so a search for NoSuchElementException found nothing. And it is not obvious what it does with things like ctl00_ContentContainer or error codes such as 0x80040217. You can check any of this with the _analyze API before you build the index:

curl --cacert http_ca.crt -u elastic -H 'Content-Type: application/json' \
  https://localhost:9200/_analyze \
  -d '{"analyzer": "standard", "text": "OpenQA.Selenium.NoSuchElementException"}'

What I wanted: split on whitespace and punctuation (dots, underscores, colons, brackets), but do not split camelCase names and do not split letters from digits. Then NoSuchElementException stays one token, ctl00 stays one token, and the dotted name becomes three tokens in order, so a phrase search for the full name still works.

SETTINGS = {
    "number_of_shards": 1,
    "number_of_replicas": 0,
    "analysis": {
        "filter": {
            "code_parts": {
                "type": "word_delimiter_graph",
                "split_on_case_change": False,
                "split_on_numerics": False,
            }
        },
        "analyzer": {
            "code": {
                "type": "custom",
                "tokenizer": "whitespace",
                "filter": ["code_parts", "lowercase"],
            }
        },
    },
}

MAPPINGS = {
    "properties": {
        "run_id": {"type": "keyword"},
        "build_id": {"type": "keyword"},
        "test_name": {
            "type": "keyword",
            "fields": {"text": {"type": "text", "analyzer": "code"}},
        },
        "outcome": {"type": "keyword"},
        "fingerprint": {"type": "keyword"},
        "exc_type": {"type": "keyword"},
        "message": {"type": "text", "analyzer": "code"},
        "stack_trace": {"type": "text", "analyzer": "code"},
        "log": {"type": "text", "analyzer": "code"},
        "timestamp": {"type": "date"},
    }
}

The Elasticsearch docs recommend the whitespace or keyword tokenizer with word_delimiter_graph, because a tokenizer that removes punctuation first leaves nothing for the filter to split on. I first tried preserve_original: true to also keep the full dotted name as a token. The docs say that option creates multi-position tokens, which need a flatten_graph filter at index time, and it can confuse phrase queries. I did not need it, so I left it out.

Replicas are 0 because there is one node. With 1 the index stays yellow forever.

Creating the index with a lifecycle policy

I write to one index per month, test-results-2022.11, through an index template. The template carries the settings, the mapping and an ILM policy that deletes the index after 90 days.

import os
from elasticsearch import Elasticsearch, helpers

es = Elasticsearch(
    "https://localhost:9200",
    ca_certs="http_ca.crt",
    basic_auth=("elastic", os.environ["ES_PASSWORD"]),
)

es.ilm.put_lifecycle(
    name="test-results",
    policy={"phases": {"delete": {"min_age": "90d", "actions": {"delete": {}}}}},
)

es.indices.put_index_template(
    name="test-results",
    index_patterns=["test-results-*"],
    template={
        "settings": {**SETTINGS, "index.lifecycle.name": "test-results"},
        "mappings": MAPPINGS,
    },
)

Without rollover, ILM counts min_age from the index creation date, so each monthly index is deleted about three months after it was created. If you do not want ILM, a monthly cron job that calls es.indices.delete(index="test-results-2022.08") does the same thing. I like ILM here because nobody has to remember the job.

Old data is rarely useful anyway. When a test has not failed with a message for three months, the page has usually changed.

Bulk indexing from Python

The documents come from the same TRX parser as in the previous post. The _id is the run id plus the test name, so loading the same run twice overwrites instead of creating duplicates.

from datetime import datetime


def actions(run_id, build_id, started, results):
    index = "test-results-" + datetime.fromisoformat(started[:19]).strftime("%Y.%m")
    for r in results:
        yield {
            "_index": index,
            "_id": f"{run_id}:{r['test_name']}",
            "_source": {
                "run_id": run_id,
                "build_id": str(build_id),
                "test_name": r["test_name"],
                "outcome": r["outcome"],
                "fingerprint": r.get("fingerprint"),
                "exc_type": r.get("exc_type"),
                "message": r["message"],
                "stack_trace": r["stack_trace"],
                "log": r["stdout"][:1_000_000],
                "timestamp": started,
            },
        }


ok, errors = helpers.bulk(
    es, actions(run_id, build_id, started, results),
    chunk_size=200, raise_on_error=False,
)
if errors:
    print(f"{len(errors)} documents failed, first: {errors[0]}")

Two notes. I cut the log at one million characters, because highlighting on a longer field fails by default (index.highlight.max_analyzed_offset). And I use raise_on_error=False and print the errors, because one bad document should not stop a nightly load. If your logs are large, also look at max_chunk_bytes.

The queries I run most

Where did this stack trace line appear? A match_phrase on the stack trace, only failures, last two weeks:

resp = es.search(
    index="test-results-*",
    query={
        "bool": {
            "must": [{"match_phrase": {"stack_trace": "ContactPage.WaitForSaved"}}],
            "filter": [
                {"term": {"outcome": "Failed"}},
                {"range": {"timestamp": {"gte": "now-14d"}}},
            ],
        }
    },
    source_includes=["run_id", "test_name", "fingerprint", "timestamp"],
    sort=[{"timestamp": "desc"}],
    size=50,
)
for hit in resp["hits"]["hits"]:
    print(hit["_source"])

Because of the analyzer, ContactPage.WaitForSaved becomes two tokens and the phrase query wants them next to each other. That is what I want.

Search inside one run’s logs with highlights, so I can see the line without opening the whole log:

resp = es.search(
    index="test-results-*",
    query={
        "bool": {
            "must": [{"match_phrase": {"log": "0x80040217"}}],
            "filter": [{"term": {"run_id": run_id}}],
        }
    },
    highlight={"fields": {"log": {}}},
)

Which fingerprints go with this text? An aggregation on the keyword field, no hits:

resp = es.search(
    index="test-results-*",
    query={"match": {"log": "session expired"}},
    aggs={"by_fp": {"terms": {"field": "fingerprint", "size": 10}}},
    size=0,
)
for b in resp["aggregations"]["by_fp"]["buckets"]:
    print(b["key"], b["doc_count"])

This one connects the search with the fingerprint table. Somebody pastes a line from a log, and the answer is “this is fingerprint 3fa1c09e2b7d, it has been around since September, and here is the work item”.

When PostgreSQL full-text search would have been enough

Honestly, for the message and the stack trace alone, PostgreSQL would have done the job. The data was already there. A tsvector column with a GIN index, to_tsvector('simple', ...) and phraseto_tsquery cover most of the queries above, and there is no extra service to run. PostgreSQL’s text parser also has its own rules for dotted names and paths, so you have to check it with ts_debug the same way as _analyze, and maybe replace dots with spaces before indexing.

What moved me to Elasticsearch was the logs. They are long, there are many of them, and I wanted highlights, a custom analyzer I could change by reindexing, and aggregations on the same query. Elasticsearch does that out of the box. The price is one more service to run: it needs memory, upgrades, and someone who knows where the password is.

My rule now: if you only search short fields that are already in PostgreSQL, start with PostgreSQL full-text search. Add Elasticsearch when you need to search large free text across many runs and people use it every week. For us that happened after a few months.