RousselTMLEARNING

TP · New Relic: from discovery to expertise

Lab: Instrument an application and a host with correction

The correction is integrated into the TP (See the green boxes)

What you will learn in this TP
  • Install an APM agent without changing code
  • Generate traffic and read transactions, Apdex and errors
  • Deploy the infrastructure agent
  • Check collection with NRQL
Mode :

All steps and instructions are shown. Recommended for this lab: guided

Introduction #

Context. Your company's online shop is slow at peak times, and nobody knows why. You instrument the order service and the server hosting it to finally get numbers.

Prerequisites: a free New Relic account (license key), a machine with Docker, curl and jq  ·  Estimated time: 40 min

A boutique-tp application and a tp-poste host visible in New Relic, with transactions, errors, logs and system metrics.

Setup #

Guided steps, with their solution.

  1. 1. Get the license key

    Why? The license key authenticates data ingest; a user key would not work.

    In New Relic, open API keys and copy an INGEST - LICENSE key. Export it in NEW_RELIC_LICENSE_KEY without writing it to a versioned file.
    See the correction
    read -rsp 'License key: ' NEW_RELIC_LICENSE_KEY && export NEW_RELIC_LICENSE_KEY
    echo ${NEW_RELIC_LICENSE_KEY: -4}   # must print NRAL
  2. 2. Instrument the application

    Why? newrelic-admin run-program loads the agent before Flask: no code line to change.

    Create the Flask order application, its Dockerfile with the newrelic==14.3.0 agent, then run the boutique container on port 8000.
    See the correction
    mkdir -p ~/nr-tp && cd ~/nr-tp
    export NEW_RELIC_LICENSE_KEY='<license key, ends with NRAL>'
    cat > app.py <<'EOF'
    import random, time
    from flask import Flask, abort
    
    app = Flask(__name__)
    
    @app.get('/')
    def index():
        return 'boutique ok'
    
    @app.get('/commande/<int:n>')
    def commande(n):
        time.sleep(random.uniform(0.05, 0.3) if n % 10 else 1.6)   # one order in ten is slow
        if n % 17 == 0:
            abort(500)                                             # one in seventeen fails
        return {'commande': n, 'statut': 'validée'}
    EOF
    cat > Dockerfile <<'EOF'
    FROM python:3.12-slim
    RUN pip install --no-cache-dir flask==3.1.3 newrelic==14.3.0
    COPY app.py .
    ENV NEW_RELIC_APP_NAME=boutique-tp \
        NEW_RELIC_DISTRIBUTED_TRACING_ENABLED=true \
        NEW_RELIC_APPLICATION_LOGGING_FORWARDING_ENABLED=true
    CMD ["newrelic-admin", "run-program", "flask", "--app", "app", "run", "--host", "0.0.0.0", "--port", "8000"]
    EOF
    docker build -t boutique-tp . && docker run -d --name boutique -p 8000:8000 -e NEW_RELIC_LICENSE_KEY boutique-tp
    docker logs boutique 2>&1 | grep -i 'new relic' | head -3
  3. 3. Generate traffic

    Why? Without traffic, the agent has nothing to measure; a steady volume gives reliable percentiles.

    Send 400 requests to /commande/<n> and count the HTTP codes returned.
    See the correction
    for i in $(seq 1 400); do curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/commande/$i; done | sort | uniq -c
    # about 377 responses 200 and 23 responses 500
  4. 4. Read APM

    Why? The APM summary answers the first three incident questions: is it slow, is it failing, since when?

    Open APM & Services › boutique-tp. Note throughput, Apdex, error rate, the slowest transaction and the error class in Errors inbox. Open a transaction trace of a slow order.
    See the correction
    Slowest transaction: WebTransaction/Function/app:commande (p95 ≈ 1.6 s, because of orders where n is a multiple of 10)
    Error: werkzeug.exceptions:InternalServerError (n multiple of 17)
    Apdex < 1: 1.6 s orders are "tolerating" (between 0.5 s and 2 s)
  5. 5. Add the infrastructure agent

    Why? Application slowness often comes from a saturated host: you need to see both layers.

    Run the infrastructure agent as a container with the name tp-poste and the env and team attributes, then check it connects.
    See the correction
    docker run -d --name newrelic-infra --network=host --cap-add=SYS_PTRACE --privileged --pid=host \
      -v "/:/host:ro" -v "/var/run/docker.sock:/var/run/docker.sock" \
      -e NRIA_LICENSE_KEY=$NEW_RELIC_LICENSE_KEY -e NRIA_DISPLAY_NAME=tp-poste \
      -e NRIA_CUSTOM_ATTRIBUTES='{"env":"tp","team":"formation"}' \
      newrelic/infrastructure:2.1.1
    docker logs newrelic-infra 2>&1 | grep -iE 'connected|error' | head -5
  6. 6. Check with NRQL

    Why? Knowing how to check collection yourself avoids concluding too quickly that "there is no problem".

    In Query your data, write four queries: transactions per name with p95, errors per class, CPU and memory of tp-poste, and the number of logs linked to the application.
    See the correction
    SELECT count(*), average(duration), percentile(duration, 95) FROM Transaction WHERE appName = 'boutique-tp' FACET name SINCE 30 minutes ago
    SELECT count(*) FROM TransactionError WHERE appName = 'boutique-tp' FACET error.class SINCE 30 minutes ago
    SELECT average(cpuPercent), average(memoryUsedPercent) FROM SystemSample WHERE displayName = 'tp-poste' TIMESERIES SINCE 30 minutes ago
    SELECT count(*) FROM Log WHERE entity.name = 'boutique-tp' SINCE 30 minutes ago

Validate your work

Check that each goal above is reached and that you get the result described in the introduction.

Difficulty level : ●●○○○ (2/5)

My progress

  • ⏱ Estimated time : ≈ 40 min

Sign in to track your progress and take notes. Sign in

⭐ Rate this lesson

3.0 initial rating from the teaching team

Sign in to rate this lesson →

💬 Questions about this lesson

No questions yet: be the first to ask for help or share your configuration.

Ask a question about this lesson →

Recommended Articles

New Relic: the observability platform at a glance

Discover New Relic: history, the unified platform and NRDB, MELT data types, entities and golden ...

New Relic APM: agents, OpenTelemetry and distributed traces

Instrumenting applications with New Relic: language agents, configuration, transactions and Apdex...

Infrastructure, logs and Kubernetes with New Relic

Monitoring servers, containers and Kubernetes with New Relic: infrastructure agent, on-host integ...

NRQL: querying all your New Relic data

Mastering NRQL, New Relic's query language: SELECT … FROM structure, filters, aggregation functio...

Datadog APM and OpenTelemetry: traces, services and correlation with logs

Instrument applications for Datadog APM (dd-trace, single step instrumentation, OpenTelemetry), u...

Installing Phoenix and tracing your first LLM application

Install Arize Phoenix (pip, Docker), send your first OpenInference traces from an OpenAI applicat...

Observability on Azure: Azure Monitor, Log Analytics, Application Insights, managed Prometheus and Grafana

A complete overview of observability on Azure: Azure Monitor (metrics, logs and Log Analytics, KQ...

Application Observability in Grafana Cloud

Application Observability in Grafana Cloud: RED metrics from traces, service map, OpenTelemetry o...

Elastic Observability: logs, infrastructure, APM and synthetics

Elastic Observability features: log exploration, infrastructure inventory with Elastic Agent and ...

Support us

♥ SUPPORT US

Support RousselTM Learning

Courses, articles, labs and certificates stay free with no intrusive ads. A voluntary contribution, of any amount you choose, pays for hosting, lab environments and new content.

Contribute with PayPal Any amount · card or PayPal accountLearn more
QR code PayPal
Or scan this QR code with your phone

Thank you, every contribution counts!