How to set CloudWatch logs retention policy for Lambda in AWS Serverless Application Model (SAM)?

0

Hi,

I am using the AWS Serverless Application Model (SAM) to create an API consisting of an API gateway and a lambda function. By default, my lambda function is attached with an AWS managed policy to send logs to CloudWatch with no expiry date. How can I perform the following:

  1. Replace the AWS managed policy with my own customer managed policy on sending logs to CloudWatch?
  2. Implement a log retention policy of 30 days?

I noticed that AWS SAM comes with some policy templates that I can use but I did not find how I can answer my two questions. https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-templates.html

Thanks.

1 回答
2
已接受的回答

Hi, @learning

You can simply create a LogGroup with the function name as shown below. Then you can set the log retention freely.

Resources:
  TestFunc:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: test-func
      CodeUri: src/handlers/test_func
      Handler: index.handler
      Runtime: python3.6
      AutoPublishAlias: live
      Timeout: 10
      MemorySize: 128
      
  TestFuncLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Sub /aws/lambda/${TestFunc}
      RetentionInDays: 14

https://dev.classmethod.jp/articles/should-create-cloudwatch-logs-log-group-when-creating-lambda-with-aws-sam/

profile picture
专家
iwasa
已回答 2 年前
profile picture
专家
已审核 5 个月前
  • Hi @iwasa, this worked like a charm! I knew it was something like this though I had to fix my indentation to get it working properly. Thanks!

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则