Skip to content
This repository was archived by the owner on Jun 12, 2018. It is now read-only.

WebSocket instrumentation

Thomas Watson Steen edited this page Jan 13, 2017 · 1 revision

This example shows how to use Opbeat to monitor WebSocket requests when using the koa-websocket module. A similar approach can be used for other frameworks and WebSocket implementations.

We'll use the opbeat.startTransaction(name[, type]) function to start a new transaction when a message is received. Though the type is optional, we recommend that you set it to the string websocket to group WebSocket requests separately from your regular transactions.

In this example we expect the message to by encoded using JSON and have a type property we can use to name the transaction. But no matter which format you use, you just need to name the transactions something that makes sense in your use-case. Just remember that transactions with the same name will be grouped together.

// Load and initialize Opbeat as the first thing in your application
var opbeat = require('opbeat').start({
  appId: '...',
  organizationId: '...',
  secretToken: '...'
})

var koa = require('koa')
var route = require('koa-route')
var websockify = require('koa-websocket')

var app = websockify(koa())

app.ws.use(route.app.ws.use(route.all('/', function* (next) {
  this.websocket.on('message', function (message) {
    message = JSON.parse(message)

    // Start a new transaction
    var name = 'ws:' + message
    var trans = opbeat.startTransaction(name, 'websocket')

    // The `handleMessage` function handles the received message and calls the
    // callback when done
    handleMessage(message, function (err) {
      if (err) {
        // Log the error with Opbeat
        opbeat.captureError(err)
        // Use the status code `500` to signal that something went wrong
        trans.result = 500
      }
      // Remember to end the transaction when done processing the message
      trans.end()
    })
  })

  yield next
}))

app.listen(3000)

Clone this wiki locally