Last active
June 15, 2023 16:46
-
-
Save sminot/3dda3a0d3cc8aac526952711f530c003 to your computer and use it in GitHub Desktop.
Print CloudWatch logs for an AWS Batch job
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import boto3 | |
import argparse | |
from datetime import datetime | |
parser = argparse.ArgumentParser() | |
parser.add_argument("job_id") | |
# Add the arguments | |
parser.add_argument( | |
'--region-name', | |
type=str, | |
default='us-west-2', | |
help='AWS Region to use' | |
) | |
args = parser.parse_args() | |
assert args.job_id is not None | |
batch = boto3.client("batch", region_name=args.region_name) | |
logs = boto3.client("logs", region_name=args.region_name) | |
# Get the log stream name | |
r = batch.describe_jobs(jobs=[args.job_id]) | |
log_stream_name = r["jobs"][0]["container"].get("logStreamName") | |
if log_stream_name is None: | |
print("Cannot find logs") | |
else: | |
# Get the log events | |
r = logs.get_log_events(logGroupName="/aws/batch/job", logStreamName=log_stream_name) | |
print("\n".join([ | |
"[%s] %s" % (datetime.fromtimestamp(i["timestamp"] / 1000), i["message"]) | |
for i in r["events"] | |
])) | |
while 'nextForwardToken' in r and "events" in r and len(r["events"]) > 0: | |
r = logs.get_log_events(logGroupName="/aws/batch/job", logStreamName=log_stream_name, nextToken=r['nextForwardToken']) | |
print("\n".join([ | |
"[%s] %s" % (datetime.fromtimestamp(i["timestamp"] / 1000), i["message"]) | |
for i in r["events"] | |
])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For me ["logStreamName"] is missing.
KeyError: 'logStreamName'