Skip to content

Instantly share code, notes, and snippets.

@olegdulin
Created April 16, 2016 11:23
Show Gist options
  • Save olegdulin/fd18906343d75142a487b9a9da9042e0 to your computer and use it in GitHub Desktop.
Save olegdulin/fd18906343d75142a487b9a9da9042e0 to your computer and use it in GitHub Desktop.
Write a "Hello World" into an AWS CloudWatch Logs service
#!/usr/local/bin/python3
import boto3
import time
logs = boto3.client('logs')
LOG_GROUP='TUTORIAL-DEV2'
LOG_STREAM='stream1'
logs.create_log_group(logGroupName=LOG_GROUP)
logs.create_log_stream(logGroupName=LOG_GROUP, logStreamName=LOG_STREAM)
timestamp = int(round(time.time() * 1000))
response = logs.put_log_events(
logGroupName=LOG_GROUP,
logStreamName=LOG_STREAM,
logEvents=[
{
'timestamp': timestamp,
'message': time.strftime('%Y-%m-%d %H:%M:%S')+'\tHello world, here is our first log message!'
}
]
)
@paulfsheridan
Copy link

Hi James, this code doesn't work, I receive NameError: name 'response' is not defined, have you had any luck with a similar solution?

@singergs
Copy link

I think the reason why you are having the error is because the response is being referenced in the function

What I think you may have todo is call the following

response = cloudwatch_logs.describe_log_streams(logGroupName='MYLOG-GROUP') and reference the token
response['logStreams'][0]['uploadSequenceToken']

response = logs.put_log_events(
    logGroupName=LOG_GROUP,
    logStreamName=LOG_STREAM,
    logEvents=[
        {
            'timestamp': timestamp,
            'message': 'Hello world, here is our second log message to the same stream!'
        }
    ],
    sequenceToken=response["nextSequenceToken"]

@Rajat456
Copy link

Rajat456 commented Jan 3, 2021

Hi Geoff Singer,

This is fine but for logging one message we are making two API one to describe and get the token
and second one to actually log the request.

But when we do actually log the request using put_log_events() we get the token in that response only
Is there anyway we can use that token itself?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment