Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Cronitor Node Library

License

NotificationsYou must be signed in to change notification settings

cronitorio/cronitor-js

Repository files navigation

Tests

Cronitor provides end-to-end monitoring for background jobs, websites, APIs, and anything else that can send or receive an HTTP request. This library provides convenient access to the Cronitor API from applications written in Javascript. See ourAPI docs for detailed references on configuring monitors and sending telemetry pings.

In this guide:

Installation

npm install cronitor --save# oryarn add cronitor

Monitoring Background Jobs

Integrate with Cron Libraries

If you are using a library likenode-cron orcron, this package provides a lightweight wrapper to enable easy monitoring integration.

constcron=require('cronitor')('cronitor_api_key');constnodeCron=require('node-cron');cron.wraps(nodeCron);// the first parameter is now the key that Cronitor will use// to send telemetry events when the jobs runs, completes or failscron.schedule('SendWelcomeEmail','*/5 * * * *',()=>{console.log('Sending welcome email to new sign ups every five minutes.');});

Monitor Any Function

Cronitor can wrap any function with telemetry pings.

constcronitor=require('cronitor')('cronitor_api_key');letasyncWorker=cronitor.wrap('background-worker',async()=>{// do some async work});// cronitor will track the start and end time and state (promise resolved or rejected).awaitasyncWorker();

Monitor long running processes

If you have a long running process (Control-Loop, Daemon, Worker, etc) you might not care about the lifecycle (start/end),and instead wish to record counts/error counts of these events instead. Use theEventobject to synchronously record loop ticks and asynchronously batch report these events to Cronitor.The following example usessqs-consumer.

constcronitor=require('cronitor')('cronitor_api_key');const{ Consumer}=require('sqs-consumer');event=newcronitor.Event('monitor-key');constapp=Consumer.create({queueUrl:'https://sqs.eu-west-1.amazonaws.com/account-id/queue-name',pollingWaitTimeMs:100,// duration to wait before repolling the queue (defaults to 0).handleMessage:async(message)=>{// do some work with `message`}});// Consumer is an event emitter and will emit one of the below events each time it is called.// a message was processedapp.on('processed_message',()=>{// increment the tick counter, no other side effects.event.tick();});// the queue is emptyapp.on('empty',()=>{// record a tick and also record that no message was processedevent.tick(0);});// an error occurred connectiong to SQSapp.on('error',(err)=>{// .error is a special "tick" method for reporting error counts.// Use it to tell Cronitor your program is still running, but encountering errors.// Error rate alert thresholds are configurable.event.error();});onconapp.start();

Sending Telemetry Events

If you want to send a heartbeat events, or want finer control over when/howtelemetry events are sent for your jobs, you can create a monitor instance and call the.ping method.

constmonitor=newcronitor.Monitor('heartbeat-monitor');// send a heartbeat eventmonitor.ping();// optional params can be passed as an object.// for a complete list see https://cronitor.io/docs/ping-apimonitor.ping({state:'run|complete|fail|ok',// run/complete|fail used to measure lifecycle of a job.env:'',// the environment this is running in (development, staging, production)message:'',// optional message that will be displayed in alerts as well as monitor activity panel on your dashboard.metrics:{duration:100,count:4500,error_count:10}});

Configuring Monitors

Yaml Configuration File

You can configure all of your monitors using a single YAML file. This can be version controlled and synced to Cronitor as part ofa deployment or build process. For details on all of the attributes that can be set, see theMonitor API documentation.

constcronitor=require('cronitor')('apiKey123');cronitor.readConfig({path:'./cronitor.yaml'});// parse the yaml file of monitorscronitor.validateConfig({path:'./cronitor.yaml'});// send monitors to Cronitor for configuration validationcronitor.applyConfig({path:'./cronitor.yaml'});// sync the monitors from the config file to Cronitorcronitor.generateConfig({path:'./cronitor.yaml'});// generate a new config file from the Cronitor API

Thecronitor.yaml file includes three top level keysjobs,checks,heartbeats. You can configure monitors under each key by definingmonitors.

jobs:nightly-database-backup:schedule:0 0 * * *notify:            -devops-alert-pagerdutyassertions:            -metric.duration < 5 minutessend-welcome-email:schedule:every 10 minutesassertions:            -metric.count > 0            -metric.duration < 30 secondschecks:cronitor-homepage:request:url:https://cronitor.ioregions:                -us-east-1                -eu-central-1                -ap-northeast-1assertions:            -response.code = 200            -response.time < 2scronitor-ping-api:request:url:https://cronitor.link/pingassertions:            -response.body contains ok            -response.time < .25sheartbeats:production-deploy:notify:alerts:['deploys-slack']events:true# send alert when the event occurs

Async Uploads

If you are working with large YAML files (300+ monitors), you may hit timeouts when trying to sync monitors in a single http request. This workload to be processed asynchronously by adding the keyasync: true to the config file. The request will immediately return abatch_key. If awebhook_url parameter is included, Cronitor will POST to that URL with the results of the background processing and will include thebatch_key matching the one returned in the initial response.

Monitor.put

You can also create and update monitors by callingMonitor.put. For details on all of the attributes that can be set see the Monitor API [documentation)(https://cronitor.io/docs/monitor-api#attributes).

constcronitor=require('cronitor')('apiKey123');constjobMonitor=awaitcronitor.Monitor.put({type:'job',key:'send-customer-invoices',schedule:'0 0 * * *',assertions:['metric.duration < 5 min'],notify:['devops-alerts-slack']});constuptimeMonitor=awaitcronitor.Monitor.put({type:'check',key:'Cronitor Homepage',schedule:'every 45 seconds',request:{url:'https://cronitor.io'},assertions:['response.code = 200','response.time < 600ms']})

Pause, Reset, Delete

constmonitor=newcronitor.Monitor('heartbeat-monitor');monitor.pause(24)// pause alerting for 24 hoursmonitor.unpause()// alias for .pause(0)monitor.ok()// reset to a passing state alias for monitor.ping({state: ok})monitor.delete()// destroy the monitor

Package Configuration

The package needs to be configured with your account'sAPI key, which is available on theaccount settings page. You can also optionally specify anapi_version, anenvironment, a requesttimeout, and a cronitorregion.

These can also be supplied using the environment variablesCRONITOR_API_KEY,CRONITOR_API_VERSION,CRONITOR_ENVIRONMENT,CRONITOR_TIMEOUT,CRONITOR_REGION.

constcronitor=require('cronitor')('cronitor_api_key',{apiVersion:'2020-10-01',environment:'staging',timeout:5000,region:'eu'});

Contributing

Pull requests and features are happily considered! By participating in this project you agree to abide by theCode of Conduct.

To contribute

Fork, then clone the repo:

git clone git@github.com:your-username/cronitor-js.git

Set up your machine:

npm install

Make sure the tests pass:

npm test

Make your change. Add tests for your change. Make the tests pass:

npm test

Push to your fork andsubmit a pull request

Packages

No packages published

Contributors9


[8]ページ先頭

©2009-2025 Movatter.jp