Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomoyk/3918bd2859e53b60787f7057c9d67103 to your computer and use it in GitHub Desktop.
Save tomoyk/3918bd2859e53b60787f7057c9d67103 to your computer and use it in GitHub Desktop.
from urllib import request
import json
import time
def send_metric(service_name, api_key, payloads):
req_url = 'https://api.mackerelio.com/api/v0/services/{}/tsdb'.format(service_name)
req_body = json.dumps(payloads).encode('utf-8')
req_method = 'POST'
req_headers = {
'Content-Type': 'application/json',
'X-Api-Key': api_key
}
req = request.Request(req_url, data=req_body, method=req_method, headers=req_headers)
try:
import ssl
contx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
with request.urlopen(req) as res:
res_body = res.read().decode('utf-8')
print(res_body)
except Exception as e:
print(e)
def send_http_get_req(url):
req = request.Request(url, method='GET')
try:
time_begin = time.time()
with request.urlopen(req) as res:
time_diff = time.time() - time_begin
return (res.status, time_diff)
except Exception as e:
print(e)
return (None, None)
def main():
# check http-server
sample = send_http_get_req('http://example.com/')
print("samp:", sample)
# send to mackerel
current_date = int(time.time())
req_payloads = [
{
"name": "Sample.resStatus",
"time": current_date,
"value": sample[0]
},
{
"name": "Sample.resTime",
"time": current_date,
"value": sample[1]
}
]
send_metric(service_name='hoge', api_key='kjhdlfhsadkjfhdskjfsfhlkjsafdhlkjfhkjdhdlkjfhskjdfhskjfh', payloads=req_payloads)
if __name__ == '__main__':
main()
from urllib import request
import json
import time
def send_metric(service_name, api_key, payloads):
req_url = 'https://api.mackerelio.com/api/v0/services/{}/tsdb'.format(service_name)
req_body = json.dumps(payloads).encode('utf-8')
req_method = 'POST'
req_headers = {
'Content-Type': 'application/json',
'X-Api-Key': api_key
}
req = request.Request(req_url, data=req_body, method=req_method, headers=req_headers)
try:
import ssl
contx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
with request.urlopen(req) as res:
res_body = res.read().decode('utf-8')
print(res_body)
except Exception as e:
print(e)
def main():
current_date = int(time.time())
req_payloads = [
{
"name": "Sample.resStatus",
"time": current_date,
"value": 200
},
{
"name": "Sample.resTime",
"time": current_date,
"value": 300,
}
]
send_metric(service_name='hoge', api_key='kjhdlfhsadkjfhdskjfsfhlkjsafdhlkjfhkjdhdlkjfhskjdfhskjfh', payloads=req_payloads)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment