By default, CloudWatch log groups created by Lambda functions have an unlimited retention time. For cost optimization purposes, you should set a retention duration on all log groups. For log archival, export and set cost-effective storage classes that best suit your needs.
Referencing the function name in the log group
This rule works by matching a Lambda function name in the CloudWatch log group name. For CloudFormation, it supports Fn::Join, Fn::Sub, and hard-coding the Lambda function name into the log group name.
Here are some examples of valid implementations:
1 2 3 4 5 6 7 8 9101112131415
Resources:Function:Type:AWS::Serverless::FunctionProperties:# Omitting other propertiesLogGroup:Type:AWS::Logs::LogGroupProperties:LogGroupName:Fn::Join:-""--"/aws/lambda/"-!RefFunctionRetentionInDays:7
1 2 3 4 5 6 7 8 91011
Resources:Function:Type:AWS::Serverless::FunctionProperties:# Omitting other propertiesLogGroup:Type:AWS::Logs::LogGroupProperties:LogGroupName:!Sub"/aws/lambda/${Function}"RetentionInDays:7
1 2 3 4 5 6 7 8 9101112
Resources:Function:Type:AWS::Serverless::FunctionProperties:# Omitting other propertiesFunctionName:my_function_nameLogGroup:Type:AWS::Logs::LogGroupProperties:LogGroupName:"/aws/lambda/my_function_nameRetentionInDays:7
Disabled for Terraform
This rule is disabled for Terraform, as the current linter only support static values in expressions. See this issue for more information.
Since serverless-rules evaluate infrastructure-as-code template, it cannot check if you use a solution that will automatically change the configuration of log groups after the fact.
import{Code,Function,Runtime}from'@aws-cdk/aws-lambda';import{LogGroup,RetentionDays}from'@aws-cdk/aws-logs';exportclassMyStackextendscdk.Stack{constructor(scope: cdk.Construct,id: string,props?: cdk.StackProps){super(scope,id,props);constmyFunction=newFunction(scope,'MyFunction',{code: Code.fromAsset('src/hello/'),handler:'main.handler',runtime: Runtime.PYTHON_3_8,});// Explicit log group that refers to the Lambda functionconstmyLogGroup=newLogGroup(scope,'MyLogGroup',{logGroupName:`/aws/lambda/${myFunction.functionName}`,retention: RetentionDays.ONE_WEEK,});}}
Resources:Function:Type:AWS::Serverless::FunctionProperties:CodeUri:.Runtime:python3.8Handler:main.handlerTracing:Active# Explicit log group that refers to the Lambda functionLogGroup:Type:AWS::Logs::LogGroupProperties:LogGroupName:!Sub"/aws/lambda/${Function}"# Explicit retention timeRetentionInDays:7
1 2 3 4 5 6 7 8 910
provider:name:awsruntime:python3.8lambdaHashingVersion:'20201221'# This will automatically create the log group with retentionlogRetentionInDays:14functions:hello:handler:handler.hello