在AWS Lambda中实现高效日志记录的最佳实践是使用Lambda提供的内置日志记录功能并结合使用云监控服务。以下是一些示例代码:
import logging
def lambda_handler(event, context):
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Log the input event
logger.info('Received event: ' + json.dumps(event))
import boto3
import logging
def lambda_handler(event, context):
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Create CloudWatch Logs client
cloudwatch_logs = boto3.client('logs')
# Log the input event
logger.info('Received event: ' + json.dumps(event))
# Send log messages to CloudWatch Logs
cloudwatch_logs.create_log_group(logGroupName='/aws/lambda/my-function')
cloudwatch_logs.create_log_stream(logGroupName='/aws/lambda/my-function', logStreamName=context.log_stream_name)
cloudwatch_logs.put_log_events(logGroupName='/aws/lambda/my-function', logStreamName=context.log_stream_name, logEvents=[{'timestamp': int(time.time() * 1000), 'message': 'Sample log message.'}])