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
|
import boto3
import logging
import time
import datetime
import json
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def export_s3_logs(bucket_name, log_group_name, log_stream_name, days_of_logs=1, timeout=1000):
'''
today = datetime.datetime.combine(datetime.datetime.utcnow(), datetime.datetime.min.time())
day_end = today
day_start = today - datetime.timedelta(days=days_of_logs)
'''
today = datetime.datetime.combine(datetime.datetime.utcnow() + datetime.timedelta(hours=8),
datetime.datetime.min.time()) # UTC+8
day_end = today - datetime.timedelta(hours=8) # UTC
day_start = today - datetime.timedelta(days=days_of_logs, hours=8) # UTC
#print(day_start)
ts_start = '{0:.0f}'.format(((day_start - datetime.datetime(1970, 1, 1)).total_seconds())*1000)
ts_end = '{0:.0f}'.format(((day_end - datetime.datetime(1970, 1, 1)).total_seconds())*1000)
the_date = '/'.join([str(today.year), '0'+str(today.month)[-2:], '0'+str(today.day)[-2:]])
#folder_name = '/'.join([log_group_name, log_stream_name, the_date])
folder_name = '/'.join([log_group_name,the_date])
client = boto3.client('logs')
#print (ts_start, ts_end)#, day_start, day_end,the_date
task_id = client.create_export_task(
logGroupName=log_group_name,
#logStreamNamePrefix=log_stream_name,
fromTime=int(ts_start),
to=int(ts_end),
destination=bucket_name,
destinationPrefix=folder_name
)['taskId']
i = 1
while i<timeout:
response = client.describe_export_tasks(
taskId=task_id
)
status = response['exportTasks'][0]['status']
if status == 'COMPLETED':
result = True
break
elif status != 'RUNNING':
result = False
break
i += 1
time.sleep(interval)
return result
def lambda_handler(event, context):
region = 'cn-northwest-1' # 日志组所在区域
bucket_name = '<bucket name>' #同区域内的S3桶名称
log_group_name = '<log group name>' #日志组名称
log_stream_name = '1' #默认即可
log_export_days = 1 #默认即可
export_s3_logs(bucket_name, log_group_name, log_stream_name, log_export_days)
|