For the complete documentation index, see llms.txt. Markdown versions are available by appending .md to documentation URLs.

Monitor AWS ELB Access Logs and CloudWatch Metrics

SigNoz Cloud - This page applies to SigNoz Cloud editions.
Self-Host - This page applies to self-hosted SigNoz editions.

Overview

SigNoz can collect two kinds of data from your AWS Elastic Load Balancers (ELB):

  • Access logs: ELB writes access logs to an S3 bucket. An AWS Lambda function reads each new log file and sends its lines to SigNoz. The function parses Classic Load Balancer and Application Load Balancer (ALB) logs.
  • Metrics: The Prometheus CloudWatch Exporter reads CloudWatch metrics such as RequestCount, Latency, and HealthyHostCount, and an OpenTelemetry Collector sends them to SigNoz.

Prerequisites

  • An AWS account with permissions to create S3 buckets, Lambda functions, and IAM policies.
  • A SigNoz Cloud account or a Self-Hosted SigNoz instance.
  • For metrics only:
    • An OpenTelemetry Collector that sends data to SigNoz.
    • Java 11 or newer for the JAR file, or Docker for the container.
    • AWS credentials with the cloudwatch:ListMetrics and cloudwatch:GetMetricStatistics permissions, from environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY), an IAM role, or ~/.aws/credentials.

Collect Access Logs

S3 invokes the Lambda function each time ELB writes a new log file to the bucket. The function reads that one file and sends its log lines to SigNoz.

Step 1. Send ELB access logs to an S3 bucket

  1. In the Amazon S3 console, click Create bucket, enter a unique bucket name, select the region of your load balancer, and click Create bucket.
S3 bucket creation form
Fill up bucket details
  1. Turn on access logs for your load balancer and select this bucket. See Enable access logs for your Classic Load Balancer or Enable access logs for your Application Load Balancer.

ELB writes the logs under AWSLogs/<account-id>/elasticloadbalancing/. Classic Load Balancer writes plain .log files, and ALB writes gzipped .log.gz files.

Step 2. Create the Lambda function

  1. In the AWS Lambda console, go to Functions and click Create function.
Create Lambda function from AWS Console
Create Lambda function from AWS Console
  1. Select Author from scratch and enter a function name.
Lambda function creation with Author from scratch selected
Choose the Author from scratch and fill up other details
  1. Select Python 3.x as the runtime and x86_64 as the architecture. Under Execution role, select Create a new role with basic Lambda permissions. Step 3 adds the S3 permission to this role.
Lambda runtime and role configuration
Choose Create a new role here
  1. Click Create function.
Lambda function created successfully
Your barebones Lambda function is created now

Step 3. Let the function read the log bucket

  1. On the function page, go to Configuration and select Permissions.
Lambda function Configuration tab showing Permissions section
Choosing execution role from Configurations tab
  1. Click the execution role name under Role name. The role opens in IAM. Click Add permissions, then select Create inline policy.
IAM role Permissions policies panel with the Add permissions menu open and Create inline policy highlighted
Create an inline policy for the Lambda execution role
  1. In the policy editor, select JSON and replace the content with this policy. The policy lets the function read objects in your log bucket, and nothing else.

    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": "s3:GetObject",
                "Resource": "arn:aws:s3:::<name_of_your_bucket>/*"
            }
        ]
    }

    Replace <name_of_your_bucket> with the name of the bucket that stores your ELB logs.

IAM policy editor in JSON mode with an s3:GetObject statement for the log bucket
The s3:GetObject policy in the JSON editor
  1. Click Next, enter a policy name, for example elb-logs-s3-read, and click Create policy.

The basic Lambda permissions from Step 2 let the function write its own logs to CloudWatch.

Step 4. Add the S3 trigger

  1. On the function page, click Add trigger.
Lambda function console showing Add trigger button
Add a trigger to the function.
  1. Select S3 as the source, and select your log bucket.
  2. For Event types, keep only All object create events, which is the default. Do not add delete events. The function downloads the object named in each event, so a delete event makes it fail.
  3. Set Prefix to the ELB log path, for example AWSLogs/<account-id>/elasticloadbalancing/, so that the function skips other objects in the bucket.
Lambda Add trigger form with S3 as the source, All object create events selected, and an AWSLogs prefix
Trigger the function on object create events under the ELB log prefix
  1. Click Add.

Step 5. Add the requests layer

The function uses the Python requests module, which the Lambda runtime does not include. Add it as a Lambda layer.

  1. On your computer, package the module in a zip file:

    mkdir python
    pip install --target python requests
    zip -r dependencies.zip python
  2. In the AWS Lambda console, go to Layers (not inside your function) and click Create layer.

AWS Lambda Layers page with Create Layer button
Creating a new Layer
  1. Enter a layer name, select Upload a .zip file, and upload dependencies.zip. Select the same architecture and the Python 3.x runtime as your function, then click Create.
Layer configuration page with upload zip file option
Uploading the requirements.zip file to later add it as a layer
  1. Go to your function, scroll to the Layers section, and click Add a layer.
Lambda function Layers section with Add a layer button
Add a layer to your Lambda function
  1. Select Custom layers, select your layer and its version, and click Add.
Add layer dialog showing Custom layers option and layer selection dropdown
Choose your layer name

Step 6. Add the function code

Replace the code in lambda_function.py with the code below, and click Deploy. The function reads the bucket name and the object key from the S3 event, downloads only that object, and sends its log lines to SigNoz. It parses both access log formats:

  • Classic Load Balancer: plain .log files, parsed with CLASSIC_HEADERS.
  • Application Load Balancer (ALB): gzipped .log.gz files, parsed with ALB_HEADERS.

The function skips all other objects, and it skips empty files. It streams each file and sends its lines in batches of 1,000 (BATCH_SIZE), so that a large log file does not fill the function's memory. It sets each log's timestamp to the request time in the log line, not to the time SigNoz receives it. If SigNoz returns an HTTP error, the function fails, so that Lambda retries the event. A retry sends the batches of that file again, so a failed file can arrive twice.

lambda_function.py
import gzip
import urllib.parse
from datetime import datetime
import boto3
import requests
import shlex
 
# Create an S3 client
s3 = boto3.client('s3')
 
# Field names of an Application Load Balancer (ALB) log line, in order
ALB_HEADERS = ["type", "time", "elb", "client:port", "target:port", "request_processing_time", "target_processing_time", "response_processing_time", "elb_status_code", "target_status_code", "received_bytes", "sent_bytes", "request","user_agent", "ssl_cipher", "ssl_protocol", "target_group_arn", "trace_idd", "domain_name", "chosen_cert_arn", "matched_rule_priority", "request_creation_time", "actions_executed", "redirect_url", "error_reason", "target:port_list", "target_status_code_list", "classification", "classification_reason", "conn_trace_id", "transformed_host", "transformed_uri", "request_transform_status", "ip_address", "target_error_code", "elb_error_code"]
 
# Field names of a Classic Load Balancer log line, in order
CLASSIC_HEADERS = ["time", "elb", "client:port", "backend:port", "request_processing_time", "backend_processing_time", "response_processing_time", "elb_status_code", "backend_status_code", "received_bytes", "sent_bytes", "request", "user_agent", "ssl_cipher", "ssl_protocol"]
 
# Function to convert a log line into a JSON object
def convert_log_line_to_json(line, headers):
    # Split the log line on spaces, and keep each quoted field together
    res = shlex.split(line, posix=False)
 
    # Remove the double quotes around quoted fields
    res = [v[1:-1] if len(v) > 1 and v[0] == v[-1] == '"' else v for v in res]
 
    # Send each field as an attribute and the raw line as the log body
    record = dict(zip(headers, res))
    record['body'] = line
 
    # Use the request time from the log line as the log timestamp, in nanoseconds
    try:
        t = datetime.fromisoformat(record['time'])
        record['timestamp'] = int(t.timestamp()) * 10**9 + t.microsecond * 1000
    except (KeyError, ValueError):
        pass  # SigNoz uses the time it received the log
    return record
 
# Number of log lines in each request to SigNoz
BATCH_SIZE = 1000
 
# Send one batch of log records, and fail the invocation on an HTTP error, so that Lambda retries the event
def send(http_url, req_headers, batch):
    response = requests.post(http_url, json=batch, headers=req_headers, timeout=30)
    response.raise_for_status()
    return response.status_code
 
# Lambda function handler
def lambda_handler(event, context):
    req_headers = {
        'signoz-ingestion-key': '<your-ingestion-key>',
        'Content-Type': 'application/json'
    }
    # Specify the HTTP endpoint for sending the data
    http_url = 'https://ingest.<region>.signoz.cloud:443/logs/json'
 
    # Process only the objects that triggered this event
    for record in event['Records']:
        bucket_name = record['s3']['bucket']['name']
        # S3 URL-encodes the object key in the event
        file_key = urllib.parse.unquote_plus(record['s3']['object']['key'])
 
        # ALB writes gzipped .log.gz files, Classic writes plain .log files
        if file_key.endswith('.log.gz'):
            headers = ALB_HEADERS
        elif file_key.endswith('.log'):
            headers = CLASSIC_HEADERS
        else:
            continue
 
        # Stream the log file, and decompress it if it is gzipped, so that a large file does not fill the memory
        body = s3.get_object(Bucket=bucket_name, Key=file_key)['Body']
        stream = gzip.GzipFile(fileobj=body) if file_key.endswith('.gz') else body.iter_lines()
 
        # Send the lines in batches of BATCH_SIZE. A retry after a failed batch sends the earlier batches again.
        batch, sent = [], 0
        for raw in stream:
            line = raw.decode('utf-8').strip()
            if line:
                batch.append(convert_log_line_to_json(line, headers))
            if len(batch) == BATCH_SIZE:
                status = send(http_url, req_headers, batch)
                sent, batch = sent + len(batch), []
        if batch:
            status = send(http_url, req_headers, batch)
            sent += len(batch)
        if not sent:
            continue
 
        # Print information about the sent data and the response received
        print(f"Sent {sent} lines from s3://{bucket_name}/{file_key}. Response: {status}")

Verify these values:

Each field in a log line maps to one name in the header list for its format. SigNoz stores each field as a log attribute, without the surrounding quotes, and the raw log line as the log body. The ALB list names the trace field trace_idd, because the HTTP logs endpoint reserves trace_id for a hex trace ID. Here is a raw Classic Load Balancer log line:

2015-05-13T23:39:43.945958Z my-loadbalancer 192.168.131.39:2817 10.0.0.1:80 0.000073 0.001048 0.000057 200 200 0 29 "GET http://www.example.com:80/ HTTP/1.1" "curl/7.38.0" - -

Here is a raw ALB log line:

https 2024-01-01T23:58:03.391277Z app/abc-prod-alb/0b46e552ds5b44da 35.244.22.76:41802 192.1.0.114:80 0.000 1.077 0.000 200 200 1430 923 "POST https://api.abcs.com:4463/suporodv2/v1/get-result/ HTTP/1.1" "SFDC-Callout/59.0" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 arn:aws:elasticloadbalancing:ap-south-1:8429181216651:targetgroup/ecs-Sabc-P-Private-SU-API/02f1623fsddec2691ce "Root=1-65343518a-72123e913f71cb2e20213a3ea9" "api.example-sabcs.com" "session-reused" 98 2024-01-01T23:58:02.313000Z "forward" "-" "-" "192.1.1.114:80" "200" "-" "-"

Step 7. Set the timeout and test the function

The default Lambda timeout is 3 seconds. Each invocation downloads one log file and sends it to SigNoz, which can take longer for a large file.

  1. On the function page, go to Configuration > General configuration and click Edit.
  2. Set Timeout to at least 1 minute, and click Save. The function waits up to 30 seconds for each request to SigNoz.
Lambda function General Configuration showing timeout setting
Configuring execution timeout of Lambda function
  1. On the Test tab, create a test event from the S3 Put template. In the event JSON, set Records[0].s3.bucket.name to your bucket and Records[0].s3.object.key to the key of a .log or .log.gz file in it, then save the event.
Lambda test event configuration dialog with S3 PUT event template
Creating Sample event
  1. Click Test. The log output shows Sent <n> lines from s3://<bucket>/<key>. Response: 200.

Collect CloudWatch Metrics

The Prometheus CloudWatch Exporter reads ELB metrics from CloudWatch, and your OpenTelemetry Collector scrapes the exporter and sends the metrics to SigNoz. Run the exporter on a host that can reach the CloudWatch APIs, has AWS credentials, and is reachable from your Collector, for example on the same EC2 instance or VM as the Collector.

Step 1. Create the exporter configuration

Create a file named elb-metrics.yaml with the following configuration:

elb-metrics.yaml
region: <aws-region>
metrics:
  - aws_namespace: AWS/ELB
    aws_metric_name: RequestCount
    aws_dimensions: [LoadBalancerName]
    aws_statistics: [Sum]
 
  - aws_namespace: AWS/ELB
    aws_metric_name: Latency
    aws_dimensions: [LoadBalancerName]
    aws_statistics: [Average]
    aws_extended_statistics: [p99]
 
  - aws_namespace: AWS/ELB
    aws_metric_name: HealthyHostCount
    aws_dimensions: [LoadBalancerName]
    aws_statistics: [Average]
 
  - aws_namespace: AWS/ELB
    aws_metric_name: UnHealthyHostCount
    aws_dimensions: [LoadBalancerName]
    aws_statistics: [Average]
 
  - aws_namespace: AWS/ELB
    aws_metric_name: HTTPCode_Backend_2XX
    aws_dimensions: [LoadBalancerName]
    aws_statistics: [Sum]
 
  - aws_namespace: AWS/ELB
    aws_metric_name: HTTPCode_Backend_4XX
    aws_dimensions: [LoadBalancerName]
    aws_statistics: [Sum]
 
  - aws_namespace: AWS/ELB
    aws_metric_name: HTTPCode_Backend_5XX
    aws_dimensions: [LoadBalancerName]
    aws_statistics: [Sum]

Verify these values:

  • <aws-region>: The AWS region of your load balancers, for example us-east-1.

See example configurations for more service templates.

Step 2. Download and run the exporter

Download the CloudWatch Exporter JAR file using curl:

curl -LO https://repo1.maven.org/maven2/io/prometheus/cloudwatch/cloudwatch_exporter/0.16.0/cloudwatch_exporter-0.16.0-jar-with-dependencies.jar

Run the exporter with Java:

java -jar cloudwatch_exporter-0.16.0-jar-with-dependencies.jar 9106 elb-metrics.yaml

This starts the exporter on port 9106.

Verify the exporter is running by checking the metrics endpoint:

curl http://localhost:9106/metrics | grep aws_elb

You should see metrics like aws_elb_request_count_sum, aws_elb_latency_average, etc.

Step 3. Configure the OpenTelemetry Collector

Add the following prometheus receiver to your existing otel-collector-config.yaml to scrape the CloudWatch Exporter:

otel-collector-config.yaml
receivers:
  prometheus:
    config:
      scrape_configs:
        - job_name: 'elb-cloudwatch'
          scrape_interval: 60s
          static_configs:
            - targets: ['<exporter-host>:9106']

Verify these values:

  • <exporter-host>: The hostname or IP where the CloudWatch Exporter is running. Use localhost if running on the same machine.

Add prometheus to the receivers list of your existing metrics pipeline. Keep the receivers, processors, and exporters that the pipeline already has. For example, a pipeline with an otlp receiver gets this receivers list:

otel-collector-config.yaml
service:
  pipelines:
    metrics:
      receivers: [otlp, prometheus]

Restart your OpenTelemetry Collector to apply the changes.

Validate

Access logs

  1. Wait for ELB to write the next log file. ALB writes a log file every 5 minutes. Classic Load Balancer writes one every 5 or 60 minutes, and 60 is the default.
  2. In SigNoz, open the Logs Explorer and filter on elb EXISTS. Each log is one request. The log body is the raw access log line, and fields such as elb, elb_status_code, and request are attributes.
SigNoz Logs Explorer filtered on two load balancers, listing raw ALB and Classic Load Balancer access log lines
ELB access logs from an ALB and a Classic Load Balancer in the Logs Explorer
  1. Click a log line to see all of its fields.
SigNoz log details for an ALB access log line with a 502 status code, showing the raw line as the body and the parsed attributes
The parsed fields of one ALB access log line

Metrics

  1. In SigNoz, open Dashboards > New Dashboard > New Panel.
  2. In the query builder, search for metrics that start with aws_elb_, for example aws_elb_request_count_sum.
  3. Make sure that the metrics have load_balancer_name labels that match your load balancers.

Run the Parser Locally (Optional)

To test the parser on your computer before you deploy it, save the script below as local_test.py in the same folder as lambda_function.py. The script imports the parser from lambda_function.py, so you must also install boto3 and requests.

local_test.py
import os
import gzip
 
# Reuse the parser from the Lambda function in the same folder
from lambda_function import ALB_HEADERS, CLASSIC_HEADERS, BATCH_SIZE, convert_log_line_to_json, send
 
def process_log_file(file_path):
    # ALB writes gzipped .log.gz files, Classic writes plain .log files
    if file_path.endswith('.log.gz'):
        with gzip.open(file_path, 'rb') as f:
            content = f.read()
        headers = ALB_HEADERS
    else:
        with open(file_path, 'rb') as f:
            content = f.read()
        headers = CLASSIC_HEADERS
 
    lines = [l for l in content.decode('utf-8').splitlines() if l.strip()]
    if not lines:
        return
    json_data = [convert_log_line_to_json(line, headers) for line in lines]
 
    req_headers = {
        'signoz-ingestion-key': '<your-ingestion-key>',
        'Content-Type': 'application/json'
    }
    http_url = 'https://ingest.<region>.signoz.cloud:443/logs/json'
    # Send in batches, and stop on an HTTP error
    for i in range(0, len(json_data), BATCH_SIZE):
        status = send(http_url, req_headers, json_data[i:i + BATCH_SIZE])
    print(f"Sent {len(json_data)} lines from {file_path}. Response: {status}")
 
def main():
    root_folder = '<folder_name>'
 
    for root, _, files in os.walk(root_folder):
        for file in files:
            if file.endswith(('.log', '.log.gz')):
                process_log_file(os.path.join(root, file))
 
if __name__ == '__main__':
    main()

Replace <folder_name> with the folder that holds your log files, and replace <your-ingestion-key> and <region> with your values. The script reads all sub-folders and sends each file that ends in .log (Classic) or .log.gz (ALB). It stops at the first HTTP error. Then run:

python local_test.py

Troubleshooting

No logs arrive in SigNoz

Open the function's logs in CloudWatch (Monitor > View CloudWatch logs).

  • If the function does not run, make sure that the trigger prefix matches the path where ELB writes the logs, and that the trigger uses All object create events.
  • If the function runs but does not show Sent <n> lines, make sure that the object key ends in .log or .log.gz. The function skips other objects and empty files.

401 Client Error: Unauthorized

The function prints requests.exceptions.HTTPError: 401 Client Error: Unauthorized. Make sure that <your-ingestion-key> is a valid ingestion key, and that <region> matches your SigNoz Cloud region.

Unable to import module 'lambda_function'

The function fails with Unable to import module 'lambda_function': No module named 'requests'. Add the layer from Step 5, and make sure that the layer uses the same runtime and architecture as the function.

Next Steps

Get Help

If you need help with the steps in this topic, please reach out to us on SigNoz Community Slack. If you are a SigNoz Cloud user, please use in product chat support located at the bottom right corner of your SigNoz instance or contact us at cloud-support@signoz.io.

Is this page helpful

Last updated—November 20, 2026