By default, lambda functions will create their own log groups if they are given proper permissions.
Specifying a log group for a Lambda FunctionThe following CloudFormation template creates two resources:
AWS::IAM::Role
AWS::Lambda::Function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
AWSTemplateFormatVersion : '2010-09-09'
Resources :
LambdaExecutionRole :
Type : 'AWS::IAM::Role'
Properties :
AssumeRolePolicyDocument :
Version : '2012-10-17'
Statement :
- Effect : Allow
Principal :
Service :
- lambda.amazonaws.com
Action :
- sts:AssumeRole
Policies :
- PolicyName : logs
PolicyDocument :
Version : '2012-10-17'
Statement :
- Effect : Allow
Action :
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource : '*'
LambdaFunction :
Type : 'AWS::Lambda::Function'
Properties :
FunctionName : 'LambdaTest'
Handler : index.handler
Runtime : nodejs18.x
Role : !GetAtt LambdaExecutionRole.Arn
Code :
ZipFile : |
exports.handler = async (event) => {
return 'Hello World!'
}
The LambdaTest
function defaults to writing log events to a group named /aws/lambda/LambdaTest
with a default retention of Never expire
. To circumvent this behavior, a AWS::Logs::LogGroup
resource can be explicitly created.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
AWSTemplateFormatVersion : '2010-09-09'
Resources :
LambdaFunctionLogGroup :
Type : 'AWS::Logs::LogGroup'
Properties :
LogGroupName : "/aws/lambda/LambdaTest"
RetentionInDays : 1
LambdaFunction :
Type : 'AWS::Lambda::Function'
DependsOn : LambdaFunctionLogGroup
Properties :
FunctionName : 'LambdaTest'
Handler : index.handler
Runtime : nodejs18.x
Role : !GetAtt LambdaExecutionRole.Arn
Code :
ZipFile : |
exports.handler = async (event) => {
return 'Hello World!'
}
LambdaExecutionRole :
Type : 'AWS::IAM::Role'
Properties :
AssumeRolePolicyDocument :
Version : '2012-10-17'
Statement :
- Effect : Allow
Principal :
Service :
- lambda.amazonaws.com
Action :
- sts:AssumeRole
Policies :
- PolicyName : logs
PolicyDocument :
Version : '2012-10-17'
Statement :
- Effect : Allow
Action :
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource : !GetAtt LambdaFunctionLogGroup.Arn
A few aspects are different:
A new AWS::Logs::LogGroup
was created with a retention period of 1 day The LambdaTest
resource uses DependsOn: LambdaFunctionLogGroup
The LambdaExecutionRole
only allows writing logs to the LambdaFunctionLogGroup.Arn
resource Warning : If the log group already exists from a prior deployment, it will need to be deleted.