Search code examples
aws-lambdaamazon-cloudwatchamazon-cloudtrail

Enrich CloudWatch and CloudTrail with custom Lambda invocation input


Problem:

I have an application with many lambda functions. However, most of them never log anything. That makes it hard to retrieve anything when there's a problem.

  • We use CloudWatch and CloudTrail. But the CloudWatch logs are often empty (just the start/stop is shown).

  • When we do find an event, it's difficult to get a full invocation trail, because each lambda has its own log group, so we often have to look through multiple log files. Which basically CloudTrail could help us with ...

  • However, CloudTrail isn't of much use either, because there are more than 1000 invocations each minute. While all events are unique, most of them look identical inside CloudWatch. That makes it hard to filter them. (e.g. There's no URL to filter on, as most of our events are first queued in SQS, and only later handled by a lambda. Because of that, there isn't any URL to search on in CloudTrail.)

On a positive side, for events that are coming from an SQS, we have a DLQ configured, which we can poll to see what the failed events look like. However, then still, it's hard to find the matching CloudTrail record.


Question:

To get more transparency, is there a convenient way to log the input body of all lambda invocations to CloudWatch? That would solve half of the problem.

And while doing so, is there a possibility to make recurring fields of the input searchable in CloudTrail?

Adding more metadata to a CloudTrail record would help us:

  • It would actually make it possible to filter, without hitting the 1000 results limit.
  • It would be easier to find the full CloudTrail for a given CloudWatch event or DLQ message.

Ideally, can any of this be done without changing the code of the existing lambda functions? (Simply, because there are so many of them.)


Solution

  • Have you considered emitting JSON logs from your Lambdas and using CloudWatch Logs Insights to search them? If you need additional custom metrics, I’d look at the Embedded Metric Format: https://aws.amazon.com/blogs/mt/enhancing-workload-observability-using-amazon-cloudwatch-embedded-metric-format/

    I’d also recommend taking a look at some of the capabilities provided by Lambda Power Tools: https://awslabs.github.io/aws-lambda-powertools-python/2.5.0/