Code Examples
Ready-to-use code examples for sending events to EdLog from various programming languages and platforms.
JavaScript / Node.js
Using fetch (Node.js 18+)
async function sendEvent(eventData) {
const response = await fetch('https://your-edlog-domain.com/ingest', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
project_key: 'api-server',
type: eventData.type,
name: eventData.name,
timestamp: new Date().toISOString(),
attributes: eventData.attributes,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
// Example: Send deployment event
await sendEvent({
type: 'deployment',
name: 'deploy_finished',
attributes: {
version: 'v1.2.3',
environment: 'production',
deployed_by: 'CI/CD',
duration_seconds: 120,
},
});
Using axios
const axios = require('axios');
class EdLogClient {
constructor(apiKey, baseUrl) {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
this.client = axios.create({
baseURL: baseUrl,
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
});
}
async sendEvent(projectKey, event) {
try {
const response = await this.client.post('/ingest', {
project_key: projectKey,
timestamp: new Date().toISOString(),
...event,
});
return response.data;
} catch (error) {
console.error('Error sending event:', error.response?.data || error.message);
throw error;
}
}
// Helper methods for common events
async deploymentStarted(projectKey, version, environment) {
return this.sendEvent(projectKey, {
type: 'deployment',
name: 'deploy_started',
attributes: { version, environment },
});
}
async deploymentFinished(projectKey, version, environment, status) {
return this.sendEvent(projectKey, {
type: 'deployment',
name: status === 'success' ? 'deploy_finished' : 'deploy_failed',
severity: status === 'success' ? 'info' : 'error',
attributes: { version, environment, status },
});
}
async recordMetric(projectKey, metricName, value, unit) {
return this.sendEvent(projectKey, {
type: 'metric',
name: metricName,
attributes: { value, unit },
});
}
}
// Usage
const edlog = new EdLogClient('YOUR_API_KEY', 'https://your-edlog-domain.com');
await edlog.deploymentStarted('api-server', 'v1.2.3', 'production');
Python
Using requests
import requests
from datetime import datetime
import json
class EdLogClient:
def __init__(self, api_key, base_url):
self.api_key = api_key
self.base_url = base_url
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
})
def send_event(self, project_key, event_type, event_name, attributes=None, **kwargs):
"""Send an event to EdLog"""
payload = {
'project_key': project_key,
'type': event_type,
'name': event_name,
'timestamp': datetime.utcnow().isoformat() + 'Z',
'attributes': attributes or {}
}
# Add optional fields
for key in ['severity', 'channel', 'correlation_id', 'labels']:
if key in kwargs:
payload[key] = kwargs[key]
response = self.session.post(
f'{self.base_url}/ingest',
data=json.dumps(payload)
)
response.raise_for_status()
return response.json()
def deployment(self, project_key, status, version, environment, **attributes):
"""Send deployment event"""
event_names = {
'started': 'deploy_started',
'finished': 'deploy_finished',
'failed': 'deploy_failed',
'rolled_back': 'deploy_rolled_back'
}
return self.send_event(
project_key,
'deployment',
event_names.get(status, status),
attributes={
'version': version,
'environment': environment,
**attributes
}
)
def error(self, project_key, error_class, message, **attributes):
"""Send error event"""
return self.send_event(
project_key,
'error',
'exception',
severity='error',
attributes={
'error_class': error_class,
'error_message': message,
**attributes
}
)
def metric(self, project_key, metric_name, value, unit='count'):
"""Send metric event"""
return self.send_event(
project_key,
'metric',
metric_name,
attributes={
'value': value,
'unit': unit
}
)
# Usage
client = EdLogClient('YOUR_API_KEY', 'https://your-edlog-domain.com')
# Send deployment event
client.deployment('api-server', 'finished', 'v1.2.3', 'production',
deployed_by='GitHub Actions',
commit_sha='abc123')
# Send error event
client.error('api-server', 'DatabaseError', 'Connection timeout',
user_id='user123',
request_url='/api/users')
# Send metric
client.metric('api-server', 'cpu_usage', 45.2, 'percent')
Ruby
Using net/http
require 'net/http'
require 'json'
require 'time'
class EdLogClient
def initialize(api_key, base_url)
@api_key = api_key
@base_url = base_url
end
def send_event(project_key:, type:, name:, attributes: {}, **options)
uri = URI("#{@base_url}/ingest")
payload = {
project_key: project_key,
type: type,
name: name,
timestamp: Time.now.utc.iso8601,
attributes: attributes
}.merge(options)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
request = Net::HTTP::Post.new(uri)
request['Authorization'] = "Bearer #{@api_key}"
request['Content-Type'] = 'application/json'
request.body = payload.to_json
response = http.request(request)
unless response.code.to_i.between?(200, 299)
raise "EdLog API error: #{response.code} - #{response.body}"
end
JSON.parse(response.body)
end
# Deployment helper
def deploy_event(project_key, status, version:, environment:, **attrs)
send_event(
project_key: project_key,
type: 'deployment',
name: "deploy_#{status}",
attributes: { version: version, environment: environment }.merge(attrs)
)
end
# Error tracking helper
def track_error(project_key, exception, context = {})
send_event(
project_key: project_key,
type: 'error',
name: 'exception',
severity: 'error',
attributes: {
error_class: exception.class.name,
error_message: exception.message,
stack_trace: exception.backtrace&.first(10)&.join("\n")
}.merge(context)
)
end
# Metric helper
def send_metric(project_key, name, value, unit: 'count')
send_event(
project_key: project_key,
type: 'metric',
name: name,
attributes: { value: value, unit: unit }
)
end
end
# Usage in Rails application
client = EdLogClient.new(ENV['EDLOG_API_KEY'], ENV['EDLOG_URL'])
# In deployment script
client.deploy_event('my-app', 'started',
version: ENV['GIT_SHA'],
environment: Rails.env)
# In error handler
begin
# Your code
rescue => e
client.track_error('my-app', e,
user_id: current_user&.id,
request_url: request.url)
raise
end
# In background job
client.send_metric('my-app', 'jobs_processed', 100)
client.send_metric('my-app', 'memory_usage', 512, unit: 'MB')
Bash / Shell Scripts
Deployment Script
#!/bin/bash
# EdLog configuration
EDLOG_URL="https://your-edlog-domain.com"
EDLOG_API_KEY="YOUR_API_KEY"
PROJECT_KEY="api-server"
# Function to send event
send_event() {
local event_type=$1
local event_name=$2
local attributes=$3
curl -s -X POST "${EDLOG_URL}/ingest" \
-H "Authorization: Bearer ${EDLOG_API_KEY}" \
-H "Content-Type: application/json" \
-d "{
\"project_key\": \"${PROJECT_KEY}\",
\"type\": \"${event_type}\",
\"name\": \"${event_name}\",
\"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
\"attributes\": ${attributes}
}"
}
# Deployment script with EdLog integration
deploy() {
VERSION=$1
ENVIRONMENT=$2
echo "Starting deployment of ${VERSION} to ${ENVIRONMENT}..."
# Send deployment started event
send_event "deployment" "deploy_started" "{
\"version\": \"${VERSION}\",
\"environment\": \"${ENVIRONMENT}\",
\"deployed_by\": \"${USER}\"
}"
# Your deployment logic here
if ./deploy.sh "${VERSION}" "${ENVIRONMENT}"; then
# Send success event
send_event "deployment" "deploy_finished" "{
\"version\": \"${VERSION}\",
\"environment\": \"${ENVIRONMENT}\",
\"status\": \"success\"
}"
echo "Deployment successful!"
else
# Send failure event
send_event "deployment" "deploy_failed" "{
\"version\": \"${VERSION}\",
\"environment\": \"${ENVIRONMENT}\",
\"status\": \"failed\",
\"error\": \"Deployment script failed\"
}"
echo "Deployment failed!"
exit 1
fi
}
# Usage
deploy "v1.2.3" "production"
Health Check Script
#!/bin/bash
# Monitor service health and send to EdLog
check_health() {
local url=$1
local start_time=$(date +%s%3N)
response=$(curl -s -o /dev/null -w "%{http_code}" "${url}")
local end_time=$(date +%s%3N)
local response_time=$((end_time - start_time))
local is_up="true"
local severity="info"
if [ "${response}" != "200" ]; then
is_up="false"
severity="error"
fi
# Send to EdLog
curl -s -X POST "${EDLOG_URL}/ingest" \
-H "Authorization: Bearer ${EDLOG_API_KEY}" \
-H "Content-Type: application/json" \
-d "{
\"project_key\": \"${PROJECT_KEY}\",
\"type\": \"uptime\",
\"name\": \"http_check\",
\"severity\": \"${severity}\",
\"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
\"attributes\": {
\"url\": \"${url}\",
\"status_code\": ${response},
\"response_time_ms\": ${response_time},
\"is_up\": ${is_up}
}
}"
}
# Check multiple endpoints
check_health "https://api.example.com/health"
check_health "https://app.example.com"
GitHub Actions
name: Deploy with EdLog Tracking
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Send deployment started event
run: |
curl -X POST "${{ secrets.EDLOG_URL }}/api/v1/webhooks" \
-H "Authorization: Bearer ${{ secrets.EDLOG_API_KEY }}" \
-H "Content-Type: application/json" \
-d '{
"project_key": "api-server",
"type": "deployment",
"name": "deploy_started",
"timestamp": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'",
"channel": "github",
"correlation_id": "${{ github.run_id }}",
"attributes": {
"version": "${{ github.sha }}",
"environment": "production",
"deployed_by": "${{ github.actor }}",
"branch": "${{ github.ref_name }}",
"run_id": "${{ github.run_id }}"
}
}'
- name: Deploy application
id: deploy
run: |
# Your deployment commands here
echo "Deploying..."
- name: Send deployment success event
if: success()
run: |
curl -X POST "${{ secrets.EDLOG_URL }}/api/v1/webhooks" \
-H "Authorization: Bearer ${{ secrets.EDLOG_API_KEY }}" \
-H "Content-Type: application/json" \
-d '{
"project_key": "api-server",
"type": "deployment",
"name": "deploy_finished",
"timestamp": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'",
"channel": "github",
"correlation_id": "${{ github.run_id }}",
"attributes": {
"version": "${{ github.sha }}",
"environment": "production",
"status": "success",
"deployed_by": "${{ github.actor }}"
}
}'
- name: Send deployment failure event
if: failure()
run: |
curl -X POST "${{ secrets.EDLOG_URL }}/api/v1/webhooks" \
-H "Authorization: Bearer ${{ secrets.EDLOG_API_KEY }}" \
-H "Content-Type: application/json" \
-d '{
"project_key": "api-server",
"type": "deployment",
"name": "deploy_failed",
"timestamp": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'",
"severity": "error",
"channel": "github",
"correlation_id": "${{ github.run_id }}",
"attributes": {
"version": "${{ github.sha }}",
"environment": "production",
"status": "failed",
"deployed_by": "${{ github.actor }}",
"error": "Deployment failed in GitHub Actions"
}
}'