{"id":19827491,"url":"https://github.com/os-guild/monitored","last_synced_at":"2025-05-01T14:32:15.295Z","repository":{"id":37899584,"uuid":"315031597","full_name":"OS-Guild/monitored","owner":"OS-Guild","description":"A utility for monitoring services :mag:","archived":false,"fork":false,"pushed_at":"2023-05-01T11:28:33.000Z","size":218,"stargazers_count":37,"open_issues_count":13,"forks_count":8,"subscribers_count":8,"default_branch":"main","last_synced_at":"2024-11-03T11:32:46.352Z","etag":null,"topics":["logging","monitoring","prometheus","statsd"],"latest_commit_sha":null,"homepage":"https://www.soluto.io","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/OS-Guild.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-11-22T12:25:27.000Z","updated_at":"2022-07-28T12:51:23.000Z","dependencies_parsed_at":"2024-10-13T10:03:04.133Z","dependency_job_id":"c933458a-9fab-4b81-8619-f7c6d77fe584","html_url":"https://github.com/OS-Guild/monitored","commit_stats":null,"previous_names":["soluto/monitored"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OS-Guild%2Fmonitored","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OS-Guild%2Fmonitored/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OS-Guild%2Fmonitored/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OS-Guild%2Fmonitored/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/OS-Guild","download_url":"https://codeload.github.com/OS-Guild/monitored/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224261988,"owners_count":17282267,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["logging","monitoring","prometheus","statsd"],"created_at":"2024-11-12T11:13:24.182Z","updated_at":"2024-11-12T11:13:24.834Z","avatar_url":"https://github.com/OS-Guild.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Monitored 🕵️‍♀️\n\nA utility for monitoring services\n\nMonitored is a wrapper function that writes success/error logs and [StatsD](https://github.com/statsd/statsd) metrics (gauge, increment, timing) after execution. It supports both asynchronous and synchronous functions.\n\n![GitHub Workflow Status](https://img.shields.io/github/workflow/status/Soluto/monitored/publish)\n[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/soluto/tweek/blob/master/LICENSE.md)\n[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)\n\n## Quick start\n\n### Yarn\n\n```bash\nyarn add monitored\n```\n\n### Npm\n\n```bash\nnpm install monitored\n```\n\n\u003cbr\u003e\n\n## Initialize\n\n### Call `setGlobalInstance` at the root of the project\n\nTo wire this package, you must pass an `Options` object.\n\n```ts\nimport { setGlobalInstance, Monitor } from 'monitored';\n\ninterface MonitorOptions {\n    serviceName: string; // Represents the name of the service you are monitoring (mandatory)\n    plugins: MonitoredPlugin[]; // Stats plugins, statsD and/or prometheus (mandatory)\n    logging?: {\n        // Writes success and error logs with the passed in logger (optional)\n        logger: any; // logger (mandatory)\n        logErrorsAsWarnings?: boolean; // log errors as warnings (optional)\n        disableSuccessLogs?: boolean; // When true, will not send success log. defaults to false (optional)\n    };\n    shouldMonitorExecutionStart?: boolean; // When true will log execution start and will increment a metrics. defaults to true (optional)\n    mock?: boolean; //Writes the metrics to logs instead of StatsD for debugging. defaults to false (optional)\n}\n\nsetGlobalInstance(\n    new Monitor({\n        serviceName: 'monitored-example',\n        logging: {\n            logger: logger,\n            logErrorsAsWarnings: false,\n            disableSuccessLogs: false,\n        },\n        plugins: [\n            new StatsdPlugin({\n                serviceName: 'test',\n                apiKey: 'key',\n                host: 'host',\n                root: 'root',\n            }),\n            new PrometheusPlugin(),\n        ],\n        shouldMonitorExecutionStart: true,\n    })\n);\n```\n\n\u003cbr\u003e\n\n## API\n\n### `monitored`\n\nAfter execution, a wrapper function writes success/error logs and StatsD metrics (gauge, increment, timing).\n\u003cbr\u003e\n\n#### `monitored` supports both **Asynchronous** and **Synchronous** functions:\n\n```ts\n//Async function:\nconst result = await monitored('functionName', async () =\u003e console.log('example'));\n\n//Sync function:\nconst result = monitored('functionName', () =\u003e {\n    console.log('example');\n});\n```\n\n\u003cbr\u003e\n\n### You can also pass a `options` argument to `monitored`:\n\n```ts\ntype MonitoredOptions = {\n    context?: any; //add more information to the logs\n    logResult?: boolean; //should write log of the method start and success\n    parseResult?: (e: any) =\u003e any; //custom parser for result (in case it is logged)\n    level?: 'info' | 'debug'; //which log level to write (debug is the default)\n    logAsError?: boolean; //enables to write error log in case the global `logErrorsAsWarnings` is on\n    logErrorAsInfo?: boolean //enables to write the error as info log\n    shouldMonitorError: e =\u003e boolean //determines if error should be monitored and logged, defaults to true\n    shouldMonitorSuccess: (r: T) =\u003e boolean //determines if success result should be monitored and logged, defaults to true\n    tags?: Record\u003cstring, string\u003e; //add more information/labels to metrics\n};\n```\n\n#### You can use `context` to add more information to the log, such as user ID\n\n```ts\nconst result = monitored(\n    'functionName',\n    () =\u003e {\n        console.log('example');\n    },\n    {context: {id: 'some context'}}\n);\n```\n\n#### You can use `tags` to add labels to metrics\n\n```ts\nconst result = monitored(\n    'functionName',\n    () =\u003e {\n        console.log('example');\n    },\n    {tags: {'some-label': 'some-value'}}\n);\n```\n\n#### Also, you can log the function result by setting `logResult` to `true`:\n\n```ts\nconst result = monitored(\n    'functionName',\n    () =\u003e {\n        console.log('example');\n    },\n    {context: {id: 'some context'}, logResult: true}\n);\n```\n\n### `flush`\n\nWait until all current metrics are sent to the server. \u003cbr\u003e\nWe recommend using it at the end of lambda execution to ensure all metrics are sent.\n\n```ts\nimport { getGlobalInstance } from 'monitored';\n\nconst flushTimeout: number = 2000;\nawait getGlobalInstance().flush(flushTimeout)\n```\n\n## Testing\n\n1. Create a `.env` file with `STATSD_API_KEY` and `STATSD_HOST` values\n2. Run `yarn example`\n3. Verify manually that console logs and metrics in the statsd server are valid\n\n## Contributing\n\nBefore creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the documentation.\nSee the [Contribution Guidelines](https://github.com/Soluto/monitored/blob/master/.github/CONTRIBUTING.md) if you'd like to submit a PR.\n\n## License\n\nLicensed under the MIT [License](LICENSE), Copyright © 2020-present [Soluto](https://github.com/Soluto).\n\nCrafted by the [Soluto](https://github.com/Soluto) Open Sourcerers🧙\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fos-guild%2Fmonitored","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fos-guild%2Fmonitored","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fos-guild%2Fmonitored/lists"}