Skip to content

Instantly share code, notes, and snippets.

@kosho
Created April 17, 2019 04:19
Show Gist options
  • Save kosho/4ca54871565d21e4e57a22fb8913fd9f to your computer and use it in GitHub Desktop.
Save kosho/4ca54871565d21e4e57a22fb8913fd9f to your computer and use it in GitHub Desktop.
Elastic's APM enabled web service sample code
// Elastic's APM enabled web service sample code
var apm = require('elastic-apm-node').start({
serviceName: 'Sample web service',
secretToken: '',
serverUrl: ''
})
var http = require('http');
var server = http.createServer();
var elasticsearch = require('elasticsearch');
function pi(){
var span = apm.startSpan('Calculating Pi');
var s = 0.0;
for (var i = 0; i<=1e8; i++){
s += Math.pow(-1.0, i) / (2*i + 1);
}
span.end();
return String(4*s);
}
server.on("request", function(req, res) {
if (req.url === "/") {
apm.setTransactionName(req.method + " " + req.url);
res.writeHead(200);
res.write("Directories:\n");
res.write(" / : Show this info\n");
res.write(" /pi : Calculate pi\n");
res.write(" /es : Connect to Elasticsearch\n");
res.write(" /err : Throw an exception\n");
}
else if (req.url === "/pi") {
apm.setTransactionName(req.method + " " + req.url);
res.writeHead(200);
res.write(pi());
}
else if (req.url === "/es") {
apm.setTransactionName(req.method + " " + req.url);
var esclient = new elasticsearch.Client({ host: 'localhost:9201', log: 'trace', httpAuth: 'elastic:changeme' });
esclient.ping().then(function(body){
res.writeHead(200);
res.write(JSON.stringify(body));
}, function(error) {
res.writehead(503);
res.write(JSON.stringify(error));
});
} else if (req.url === "/err") {
apm.setTransactionName(req.method + " " + req.url);
throw new Error("i'm a bug🐛");
}
else {
res.writeHead(404);
res.write("Not found");
}
res.end();
});
server.listen("8080", "localhost");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment