Create a Log stream URL for AWS CloudWatch Logs from AWS Lambda request context
Sometime we want to get the Lambda execution’s log stream URL on AWS CloudWatch Logs. And we can create […]
広告ここから
広告ここまで
目次
Sometime we want to get the Lambda execution’s log stream URL on AWS CloudWatch Logs.
And we can create this URL in your Lambda function.
Code
import { Handler } from 'aws-lambda'
export const handler: Handler = async (event, _context) => {
const logStreamURL = [
"https://console.aws.amazon.com/cloudwatch/home?region=",
process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION,
"#logsV2:log-groups/log-group/",
encodeURIComponent(_context.logGroupName),
'/log-events/',
encodeURIComponent(_context.logStreamName)
].join('')
return logStreamURL
}
Note
If you using the example code, please keep in mind we have to set an env parameter as similar to Lambda.
The code request to use AWS_REGION
or AWS_DEFAULT_REGION
parameter.So, if we execute your Lambda function outside AWS Lambda, we need to set it manually. Or, if these props are undefined, the URL should be null.
import { Context } from 'aws-lambda'
const getLogStreamURL = (context?: Context): string | null => {
const region = process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION
if (!region || !context) return null
const logStreamURL = [
"https://console.aws.amazon.com/cloudwatch/home?region=",
region,
"#logsV2:log-groups/log-group/",
encodeURIComponent(context.logGroupName),
'/log-events/',
encodeURIComponent(context.logStreamName)
].join('')
return logStreamURL
}