Skip to content

Instantly share code, notes, and snippets.

@ruanbekker
Created May 27, 2022 14:34
Show Gist options
  • Save ruanbekker/53f5147e9979812bbd9e2039f30d6a19 to your computer and use it in GitHub Desktop.
Save ruanbekker/53f5147e9979812bbd9e2039f30d6a19 to your computer and use it in GitHub Desktop.
Python Requests to ship logs to Loki API
#!/usr/bin/env python3
# docs: https://grafana.com/docs/loki/latest/api/#post-lokiapiv1push
import requests
import time
# variables
LOKI_USERNAME="x"
LOKI_PASSWORD="x"
LOKI_ENDPOINT="https://loki-api.example.com/loki/api/v1/push"
def generate_log_message(message):
headers = {"content-type":"application/json"}
data = {
"streams": [{
"stream": { "job": "python-requests", "env": "test", "level": "info" },
"values": [ [ time.time_ns(), message ] ]
}]
}
response = requests.post(LOKI_ENDPOINT, headers=headers, json=data, auth=(LOKI_USERNAME, LOKI_PASSWORD))
return response.status_code
response = generate_log_message("this is a test")
print(response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment