Skip to main content

BASH POST ElasticSearch

Looking for a way to log messages to an Elasticsearch instance, I searched and found that this would be my preferred one.

Prerequisites are to have jq and curl installed.

Write a function elk_log():

elk_log(){
    # Default configuration
    ELK_HOST="elasticsearch.rktmb.org"
    ELK_PORT=9200
    ELK_IDX="mihamina-database"

    # Overridden if ENV vars set:
    if [ -n "$GW_HOST" ]; then	ELK_HOST=$GW_HOST; fi
    if [ -n "$GW_PORT" ]; then	ELK_PORT=$GW_PORT; fi
    TSTAMP=$( date --iso-8601=sec )

    curl -H "Content-Type:application/json" \
	 -X POST --silent \
	 --data "$( jq -n \
		      --arg tstamp "$TSTAMP" \
		      --arg message "$1" \
		      '{timestamp: $tstamp, message: $message}' )" http://${ELK_HOST}:${ELK_PORT}/${ELK_IDX}/_doc
}

Then call this with:

#[...]
elk_log "MIHAMINA DATA STRUCTURE BEGIN"
#[...]
elk_log "MIHAMINA DATA STRUCTURE END"
#[...]

Thanks to https://stackoverflow.com/a/48470227