-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloud_watch_logger.py
80 lines (67 loc) · 2.64 KB
/
cloud_watch_logger.py
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import json
import boto3
from datetime import datetime, date
import os
region = os.environ['AWS_REGION']
def default(o):
if isinstance(o, (date, datetime)):
return o.isoformat()
class CloudWatchLogger(object):
"""
a logger class that publish the logs to CloudWatch
"""
def __init__(self, aws_access_key_id, aws_secret_access_key, log_group, aws_session_token=None):
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
self.aws_session_token = aws_session_token
self.log_group = log_group
if aws_session_token is None:
self.log_client = boto3.client('logs', region, aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key)
else:
self.log_client = boto3.client('logs', region, aws_session_token=aws_session_token)
self.log_list = []
def flush(self, base_name):
"""
Send the logs to CloudWatch. Logs will not show up in CloudWatch until this function is called
:param base_name: name for the log
:return:
"""
try:
response = self.log_client.describe_log_groups(
logGroupNamePrefix=self.log_group,
)
if len(response['logGroups']) == 0:
_ = self.log_client.create_log_group(
logGroupName=self.log_group
)
response = self.log_client.describe_log_streams(
logGroupName=self.log_group,
logStreamNamePrefix='log-' + base_name,
)
if len(response['logStreams']) == 0:
_ = self.log_client.create_log_stream(
logGroupName=self.log_group,
logStreamName='log-' + base_name
)
_ = self.log_client.put_log_events(
logGroupName=self.log_group,
logStreamName='log-' + base_name,
logEvents=self.log_list)
self.log_list = []
except Exception as e:
print(e)
def log(self, message, response_dict=None):
"""
Add a log entry. a timestamp will be added to each entry.
:param message:
:param response_dict: a dictionary containing a boto3 standard response
:return:
"""
if response_dict is not None:
message = message + json.dumps(response_dict, indent=4, default=default)
timestamp = datetime.now()
self.log_list.append({
'timestamp': int(timestamp.timestamp()*1000),
'message': message
})