Guide / Monitor errors in your apps, servers and scripts

Monitor errors in your apps, servers and scripts

Send what goes wrong in your own Node.js, React Native, PHP, Python, Android and iOS code, and your shell scripts, to your website's Errors page.

Before you start

Error monitoring is in early access: it is open only to accounts we invite while it is tested (see the terms). If your account has it, a website's Security scan tab in the console shows a Monitoring card.

Your website's visitors already report the errors their browsers hit, through the script tag. These libraries do the same for your own mobile apps, servers and scripts: what goes wrong lands on the same site's Errors page, each problem marked with where it came from (browser, mobile app, server, script). You need:

  • A website added to your account at app.cyberrakshak.ai and verified as yours (Verify it is yours, on the site's Security scan tab). Reports for a site that is not verified are refused.
  • Its error monitoring switched on: Monitoring → Turn on, on the same tab.

1. Make an app key

  1. In the console, open Websites, then the site, then its Security scan tab.
  2. Under Apps, servers and scripts, press Make an app key.
  3. Copy the key (it starts with crk_) and keep it somewhere safe: it is shown only this once. If it is lost, make a new one; the old one stops working at once.

The app key is a secret, like a password. Keep it out of public code and repositories: put it in an environment variable or your secrets store (the examples below read CR_MONITOR_KEY). A mobile app carries its key inside the app you ship, so someone who has the app could find it. A key can only send reports to the site's Errors page, and you can replace it at any time.

The command line can do this and the next step for you, from your project's folder: cyberrakshak init --site example.com.

2. Add the library

Add the library for your platform and start it with the key:

Node.js

Node.js 18 or later, ES modules or CommonJS. It reports uncaught exceptions (Node then exits with code 1, as it would) and unhandled promise rejections by itself; expressErrorHandler() reports Express and Connect errors that end in a 5xx.

Terminal
npm install @cyberrakshak/monitor
JavaScript
import * as monitor from '@cyberrakshak/monitor'
// CommonJS: const monitor = require('@cyberrakshak/monitor')

monitor.init({ key: process.env.CR_MONITOR_KEY, release: '1.0.0', environment: 'production' })
app.use(monitor.expressErrorHandler()) // with Express: after your routes

// an error you catch yourself
monitor.captureException(err, { route: 'nightly-import', context: { batch: 42 } })
await monitor.flush(2000) // before you call process.exit() yourself

Next.js (App Router, Node.js runtime; version 1.1.0 or later): start it in register() and hand each request error to captureRequestError. It takes the route Next.js names (POST /app/api/pay/route), never request.path (it carries the query string) and never the headers, and resolves once what is waiting is sent (at most 2 seconds), so a serverless function is not frozen before it goes. With no CR_MONITOR_KEY (a preview, your own computer) nothing starts and nothing is sent.

instrumentation.ts
import type { Instrumentation } from 'next'

export async function register() {
  if (process.env.NEXT_RUNTIME !== 'nodejs') return
  const monitor = await import('@cyberrakshak/monitor')
  monitor.init({ key: process.env.CR_MONITOR_KEY, release: process.env.VERCEL_GIT_COMMIT_SHA, environment: process.env.VERCEL_ENV })
}

export const onRequestError: Instrumentation.onRequestError = async (err, request, context) => {
  if (process.env.NEXT_RUNTIME !== 'nodejs') return
  const monitor = await import('@cyberrakshak/monitor')
  await monitor.captureRequestError(err, request, context)
}

React Native and Expo

No native modules. It reports every error that reaches React Native's global handler (fatal ones as crashes) and, in release builds on Hermes, unhandled promise rejections. Give it AsyncStorage and a crash is kept and sent at the next launch.

Terminal
npm install @cyberrakshak/react-native
# optional, to keep a crash for the next launch:
npx expo install @react-native-async-storage/async-storage   # or npm install it
TypeScript
import * as monitor from '@cyberrakshak/react-native'
import AsyncStorage from '@react-native-async-storage/async-storage'

monitor.init({ key: 'crk_…', release: '1.4.2+57', environment: 'production', storage: AsyncStorage })
monitor.setRoute('Checkout') // from your navigation's state change

// in an error boundary:
monitor.captureException(error, { componentStack: info.componentStack })

With Expo, cyberrakshak init writes the key to .env as EXPO_PUBLIC_CR_MONITOR_KEY, and key: process.env.EXPO_PUBLIC_CR_MONITOR_KEY reads it.

PHP

PHP 8.1 or later, Laravel or plain PHP. It reports uncaught exceptions and fatal errors, running out of memory too (wherever PHP still runs shutdown functions after it), and with captureErrors also warnings. What it has is sent at the end of the request or script, in at most 2 seconds, so a page is never held long.

Terminal
composer require cyberrakshak/monitor
PHP
\CyberRakshak\Monitor::init(['key' => getenv('CR_MONITOR_KEY'), 'release' => '1.0.0', 'environment' => 'production']);

try {
    chargeCard($order);
} catch (\Throwable $e) {
    \CyberRakshak\Monitor::captureException($e, ['route' => 'checkout', 'context' => ['step' => 2]]);
}

In Laravel, let Laravel report and pass each exception on. The route is then Laravel's (GET /orders/{order}).

Laravel
// config/services.php, in the array it returns
'cyberrakshak' => ['key' => env('CR_MONITOR_KEY')],

// app/Providers/AppServiceProvider.php, in boot()
\CyberRakshak\Monitor::init(['key' => config('services.cyberrakshak.key'), 'environment' => app()->environment(), 'handleExceptions' => false]);

// bootstrap/app.php
->withExceptions(fn ($e) => $e->report(fn (Throwable $t) => \CyberRakshak\Monitor::captureException($t)))

Python

Python 3.9 or later. It reports an exception that ends the program or a thread, and with LoggingHandler every ERROR log record.

Terminal
pip install cyberrakshak-monitor
Python
import logging, os
import cyberrakshak_monitor as monitor

monitor.init(key=os.environ["CR_MONITOR_KEY"], release="1.0.0", environment="production")
logging.getLogger().addHandler(monitor.LoggingHandler())  # every ERROR record

# an error you catch yourself
monitor.capture_exception(exc, route="nightly-import", context={"batch": 42})
Django (settings.py, or an AppConfig.ready())
from django.core.signals import got_request_exception
got_request_exception.connect(lambda sender, request=None, **kw: monitor.capture_exception(
    route=request.resolver_match.route if request is not None and request.resolver_match else None), weak=False)
Flask
from flask import got_request_exception, request
got_request_exception.connect(lambda sender, exception, **kw: monitor.capture_exception(
    exception, route=request.url_rule.rule if request.url_rule else None), weak=False)

Shell scripts and cron

One POSIX sh script that needs curl and awk. Put it in front of a command: the command's output and exit code are unchanged, and if it fails, its name, exit code and the last 20 lines of its standard error are reported. Its settings come from environment variables.

Terminal
curl -fsSLO https://app.cyberrakshak.ai/sdk/shell/cr-report.sh && chmod +x cr-report.sh

export CR_MONITOR_KEY=crk_…
export CR_MONITOR_ENVIRONMENT=production

./cr-report.sh run -- ./backup.sh --target s3://bucket   # runs it; if it fails, reports it
./cr-report.sh message --level error "Nightly import failed"

In cron, put cr-report.sh run -- in front of the job's command, with CR_MONITOR_KEY set. With Node.js installed, the command line's cyberrakshak run -- <command> does the same.

Android (Kotlin)

Android 5 (API 21) or later, from Kotlin or Java. It reports uncaught exceptions on any thread: each is written at once and sent at the next start. Native crashes and ANRs are not reported. The library adds the INTERNET permission to your app's manifest (most apps have it already).

settings.gradle.kts
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        maven("https://jitpack.io")
    }
}
build.gradle.kts (your app)
dependencies {
    implementation("com.github.LaabamOne-Business-Solutions-Pvt-Ltd:cyberrakshak-monitor-android:1.0.0")
}
Kotlin
import ai.cyberrakshak.monitor.CyberRakshakMonitor

// in your Application class, onCreate()
CyberRakshakMonitor.init(this, CyberRakshakMonitor.Options(key = "crk_…", release = BuildConfig.VERSION_NAME, environment = "production"))
CyberRakshakMonitor.setRoute("Checkout") // the screen now shown

// an error you catch yourself
CyberRakshakMonitor.captureException(e, context = mapOf("step" to 2))

iOS (Swift)

Swift 5.5 or later, iOS 13 or later, through Swift Package Manager. It reports uncaught Objective-C exceptions, sent at the next launch.

It does not catch Swift runtime traps (a force-unwrapped nil, an index out of range, fatalError) or signals: those end the app without a report, so report the errors you catch with captureError. It is tested on macOS and an iOS Simulator, not yet on a real iPhone.

Swift Package Manager
// Xcode: File → Add Package Dependencies…, then
//   https://github.com/LaabamOne-Business-Solutions-Pvt-Ltd/cyberrakshak-monitor-swift
// or in Package.swift:
.package(url: "https://github.com/LaabamOne-Business-Solutions-Pvt-Ltd/cyberrakshak-monitor-swift", from: "1.0.0"),
// and in your target: .product(name: "CyberRakshakMonitor", package: "cyberrakshak-monitor-swift")
Swift
import CyberRakshakMonitor

// in your App or AppDelegate, as early as you can
CyberRakshakMonitor.start(.init(key: "crk_…", release: "1.4.2+57", environment: "production"))
CyberRakshakMonitor.setRoute("Checkout") // the screen now shown

CyberRakshakMonitor.captureError(error)
CyberRakshakMonitor.captureMessage("Payment provider answered slowly")

3. Options

Every library takes the same options, each in its own language's spelling (its README on GitHub lists them). The shell script reads them from CR_MONITOR_KEY, CR_MONITOR_RELEASE, CR_MONITOR_ENVIRONMENT, CR_MONITOR_ENABLED, CR_MONITOR_SAMPLE_RATE, CR_MONITOR_CONTEXT (k=v,k2=v2) and CR_MONITOR_DEBUG.

OptionWhat it does
keyYour site's app key, crk_ and 32 letters or digits. Required: with no valid key, the library does nothing.
releaseYour version or build (letters, digits and . _ + -, at most 60), so a problem shows the release it started in.
environmentproduction, staging… (lower-case letters, digits, _ and -, at most 30).
enabledfalse sends nothing (default true), for example in development.
sampleRateFrom 0 to 1: the share of problems sent (default 1, all of them).
beforeSendGets each problem, already scrubbed. Return it, changed if you like, or nothing to drop it.
debugSays on the console or standard error what the library does, and why something was not sent. The key is never printed.
contextValues sent with every problem: at most 20, each a string (up to 300 characters), a number or true/false. From 1.1.0, a value whose name is a secret name (password, pin, iban…) is sent as [removed].
scrubNamesFrom 1.1.0: names of your own whose values are removed, like password=: whole words of letters, digits and _ . -, at most 50 (for example x-brand-key). Shell: CR_MONITOR_SCRUB_NAMES, comma-separated.
scrubPatternsFrom 1.1.0: regular expressions of your own, in the language's own syntax; what they match becomes [removed]. At most 20. Not in the shell script.

What is sent, and what never is

  • Sent, per problem: its kind (exception, crash, unhandled promise, log message, failed request, failed script), its message, its stack trace (file, line and function, never argument values), the route, screen or command (never its query string), the level, and how many times it happened and when. With each report: the library's name and version, the platform and runtime (such as node 22.4 or android 14), and your release and environment.
  • Never sent: request or response bodies, headers, cookies, sessions, form fields, what a user types, environment variables, local variables, device identifiers, location, contacts.
  • Scrubbed before anything leaves: query strings; Bearer and Basic values; the value after password, secret, token, api_key and similar names; JSON Web Tokens; keys that say what they are (crk_, sk_live_, ghp_, AKIA…); email addresses; card numbers; and from 1.1.0 bank account numbers (IBANs) and the value after authorization, cookie, signature, otp, pin, cvv, iban, bban, pan, account number, sort code, card number and bank auth id; long runs of hex digits or random-looking letters and digits. They become [removed], [token], [email], [iban] or [card]. Every library follows the same rules, scrubNames and scrubPatterns can only add to them, and the console scrubs everything again when it arrives.

You decide what your code sends, and you tell your own users about it in your privacy notice: see the terms and our privacy policy.

How sending behaves

  • Sending happens off your main path (a background thread, a timer, or the end of the request in PHP). A request takes at most 5 seconds; at exit, at most 2 seconds are spent sending what is left.
  • Repeats of one problem are counted, not sent again. At most 10 problems go in one request, each request under 64 KB.
  • If the console asks it to slow down, has a problem or does not answer, problems are kept and tried again later. Mobile libraries keep them on the device for the next launch; PHP and the shell script in a small file in the temp or cache folder.
  • If the key is not known, the site is not verified or its monitoring is off, the library drops what it has and sends nothing for an hour.
  • Nothing in a library throws into your code, and the handlers your app already had still run as they did.

4. Check that it works

  1. Report something on purpose: captureMessage (shell: cr-report.sh message) in a test build, or cyberrakshak test from the command line, which sends a test problem with the app key and checks it arrived.
  2. Open the site's Errors page in the console. Under Apps, servers and scripts, the Security scan tab also says when an app last reported.
  3. Nothing there? Start the library with debug on: it says why it did not send. Check that the site is verified and its monitoring is on.

Packages, files and source code

LibraryPackage and source
Node.js@cyberrakshak/monitor on npm · source
React Native and Expo@cyberrakshak/react-native on npm · source
PHPcyberrakshak/monitor on Packagist · source
Pythoncyberrakshak-monitor on PyPI · source
AndroidJitPack, from the source
iOSSwift Package Manager, from the source
Shellcr-report.sh, from the console

Without a package manager, every library is also one file you can download from the console, with no dependencies: the full reference lists them, and index.json gives each file's SHA-256 so you can check a download. All of them are free to use under the MIT licence.