Include CloudFront-Viewer-Country in the AWS Cloudfront logs

52 views Asked by At

Here's what I am trying to do. I have a file say (cat.jpg) in S3. Cloudfront is created with S3 as the origin. I am trying to capture location of the user who calls the cloudfront dns end point to access cat.jpg. Ex: https://myrepourl.company.com/cat.jpg. The user can be from any country across the globe.

In the Cloudfront cache behavior, header 'CloudFront-Viewer-Country' is added. I have added custom policy in the response header policy and added header 'CloudFront-Viewer-Country' in this as well.

I have associated a lambda edge function (from us-east-1) and below is the code used.

'use strict';

exports.handler = (event, context, callback) => {
   const request = event.Records[0].cf.request;   
   if(request.headers['cloudfront-viewer-country'])
   {
      print('country is '+request.headers['cloudfront-viewer-country'])
   }
   return callback(null,request);
};

Question 1 I do not see the header 'CloudFront-Viewer-Country' in the log file (stored in gz format) in logs S3 bucket. I see the IP address of the user. But I would like to see the country header as well.

Question 2 I see the header 'CloudFront-Viewer-Country' in the lambda edge logs. But I can view the lambda edge logs only corresponding to the region us-east-1 since I only have access to AWS resources only in this region. Will lambda edge logs be of any use to my requirement? If so, how can I capture lambda edge logs from all regions such that I get to see Country details of any user accessing the Cloudfront url.

1

There are 1 answers

2
Cristian On

Are you trying to collect this data to generate a report/visualization? If so, one way you could do this out-of-the-box is using the CloudFront Security Dashboard

Steps in the console:

  1. Navigate to the Security tab of your CloudFront distribution
  2. Enable WAF (if not already enabled)
  3. Enable logging in the "Request logs" section (if not already enabled)
  4. Add a filter by URI path to visualize the countries of viewers viewing that URI path

Figure 10 of this blog post shows you what the visualization will look like: https://aws.amazon.com/blogs/networking-and-content-delivery/introducing-cloudfront-security-dashboard-a-unified-cdn-and-security-experience/

If you need to do this programmatically, you can query CloudWatch Log Insights directly to pull the raw data (it's what the log analyzer in this security dashboard is doing for you in the console).