AWS Lambda CloudWatch

AWS Lambda CloudWatch

Push logs from Amazon CloudWatch to your Stack using the Logit.io API

Use a Lambda function to forward CloudWatch log events to your Logit.io Stack.

Logs

Install Integration

Please click on the Install Integration button to configure your stack for this source.

Ensure CloudWatch configuration

The unified CloudWatch agent collects logs and metrics. Configure the CloudWatch agent (opens in a new tab)

Log events preview

Read more about the metrics collected (opens in a new tab) by the CloudWatch Agent.

Once your logs arrive in CloudWatch, configure Lambda to forward them to Logit.io.

Configure Lambda function

From your Amazon Console browse to the Lambda functions and choose Create Function.

Choose Author from scratch, enter a name, select a current Node.js runtime, then choose Create function.

Create function by selecting Author from scratch

Replace the contents of index.mjs with the following handler. Keep the Lambda handler setting as index.handler.

import { gunzipSync } from "node:zlib";
 
export async function handler(input) {
  const compressed = Buffer.from(input.awslogs.data, "base64");
  const payload = JSON.parse(gunzipSync(compressed).toString("utf8"));
  if (payload.messageType === "CONTROL_MESSAGE") return;
 
  const apiKey = process.env.LOGIT_API_KEY;
  if (!apiKey) throw new Error("Set LOGIT_API_KEY");
 
  const concurrency = 10;
  for (let offset = 0; offset < payload.logEvents.length; offset += concurrency) {
    const batch = payload.logEvents.slice(offset, offset + concurrency);
    const results = await Promise.allSettled(batch.map(async (logEvent) => {
      const response = await fetch("https://@logitApiEndpoint/v2", {
        method: "POST",
        headers: {
          ApiKey: apiKey,
          "Content-Type": "application/json",
          LogType: "cloudwatch_lambda",
        },
        body: JSON.stringify({
          message: logEvent.message,
          logGroupName: payload.logGroup,
          logStreamName: payload.logStream,
          timestamp: new Date(logEvent.timestamp).toISOString(),
        }),
        signal: AbortSignal.timeout(10_000),
        redirect: "error",
      });
      await response.text();
      if (response.status === 403) return response.status;
      if (response.status !== 202) {
        throw new Error(`Logit.io returned HTTP ${response.status}`);
      }
    }));
 
    if (results.some((result) => result.status === "fulfilled" && result.value === 403)) {
      console.error(
        "Logit.io returned HTTP 403. Remove the forwarder or update LOGIT_API_KEY with an active stack's API key.",
      );
      return;
    }
 
    const failure = results.find((result) => result.status === "rejected");
    if (failure) throw failure.reason;
  }
}

The handler sends one JSON object per CloudWatch log event and makes up to 10 requests at a time. The default Logstash pipeline parses each object into a separate document. On HTTP 403, the handler logs the error and stops forwarding the payload without triggering a Lambda retry. Remove the forwarder or update it with an active stack's API key. Other request failures, including HTTP 503, fail the invocation so Lambda can retry it. A retry can resend events that already reached the queue. Set the function timeout to allow enough time to forward a full CloudWatch payload. AWS Lambda retry behaviour (opens in a new tab)

For high volumes, use Splunk HEC to batch the log events in fewer HTTP requests.

Environment variables

In the Lambda function's environment variables, set LOGIT_API_KEY to @apikey. You can also find the API key in Stack > Settings > Stack API Keys.

Save and deploy the function.

Configure CloudWatch trigger

From the Lambda designer choose to Add Trigger and select the required CloudWatch Log Group.

Add trigger in Designer

New log events in the selected log group are forwarded to your stack.

Launch OpenSearch Dashboards to View Your Data

Launch OpenSearch Dashboards

How to diagnose no data in Stack

If you don't see data appearing in your stack after following this integration, take a look at the troubleshooting guide for steps to diagnose and resolve the problem or contact our support team and we'll be happy to assist.

Use the CloudWatch event timestamp (optional)

The default pipeline uses ingestion time for @timestamp. To use the original CloudWatch event time, add this filter in Stack > Settings > Logstash Pipelines.

Edit Pipelines
if [type] == "cloudwatch_lambda" and [timestamp] {
  date {
    match => ["timestamp", "ISO8601"]
    target => "@timestamp"
  }
}

CloudWatch Lambda Overview

Sending CloudWatch data to Logit.io centralises serverless application logs for monitoring and analysis. To optimise your AWS environment further, consider exploring our Amazon CloudFront integration, which accelerates content delivery, and Amazon VPC integration, which enhances security and isolation. These integrations are a seamless addition to Logit.io's service for AWS logging (opens in a new tab).