├── package.json ├── LICENSE ├── .gitignore ├── dist └── console-cloud-watch.min.js ├── README.md └── console-cloud-watch.js /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "console-cloud-watch", 3 | "version": "0.1.1", 4 | "description": "Send your browser errors and console message to AWS CLoudWatch", 5 | "main": "console-cloud-watch.js", 6 | "scripts": { 7 | "uglify": "uglifyjs console-cloud-watch.js -c -m -o dist/console-cloud-watch.min.js", 8 | "uglify-all": "uglifyjs node_modules/stacktrace-js/dist/stacktrace.min.js node_modules/fingerprintjs2/dist/fingerprint2.min.js vendor/aws-sdk-cloudwatch-2.156.0.min.js console-cloud-watch.js -c -m -o dist/console-cloud-watch-all.min.js" 9 | }, 10 | "author": { 11 | "name": "Andrea Agili", 12 | "email": "agea@drwolf.it" 13 | }, 14 | "repository": { 15 | "type": "git", 16 | "url": "git://github.com/agea/console-cloud-watch.git" 17 | }, 18 | "license": "MIT", 19 | "dependencies": { 20 | "fingerprintjs2": "^1.5.1", 21 | "stacktrace-js": "^2.0.0" 22 | }, 23 | "devDependencies": { 24 | "uglify-js": "^3.2.0" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2017 Andrea Agili 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/node 3 | 4 | ### Node ### 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | yarn-debug.log* 10 | yarn-error.log* 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | 24 | # nyc test coverage 25 | .nyc_output 26 | 27 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 28 | .grunt 29 | 30 | # Bower dependency directory (https://bower.io/) 31 | bower_components 32 | 33 | # node-waf configuration 34 | .lock-wscript 35 | 36 | # Compiled binary addons (http://nodejs.org/api/addons.html) 37 | build/Release 38 | 39 | # Dependency directories 40 | node_modules/ 41 | jspm_packages/ 42 | 43 | # Typescript v1 declaration files 44 | typings/ 45 | 46 | # Optional npm cache directory 47 | .npm 48 | 49 | # Optional eslint cache 50 | .eslintcache 51 | 52 | # Optional REPL history 53 | .node_repl_history 54 | 55 | # Output of 'npm pack' 56 | *.tgz 57 | 58 | # Yarn Integrity file 59 | .yarn-integrity 60 | 61 | # dotenv environment variables file 62 | .env 63 | 64 | 65 | # End of https://www.gitignore.io/api/node 66 | 67 | test.html -------------------------------------------------------------------------------- /dist/console-cloud-watch.min.js: -------------------------------------------------------------------------------- 1 | !function(e,o,n){"use strict";"function"==typeof window.define&&window.define.amd?window.define(n):"undefined"!=typeof module&&module.exports?module.exports=n():o.exports?o.exports=n():o.ConsoleCloudWatch=n()}(0,this,function(){return function(e,o,n,t,c,r,s){function a(e){i.createLogStream({logGroupName:t,logStreamName:e},function(o,n){o&&"ResourceAlreadyExistsException"!==o.code?console.log(o,o.stack):(localStorage.setItem("ConsoleCloudWatch:stream",e),setInterval(function(){var e=u.splice(0);e.length&&i.putLogEvents({logEvents:e,sequenceToken:localStorage.getItem("ConsoleCloudWatch:sequenceToken"),logGroupName:t,logStreamName:localStorage.getItem("ConsoleCloudWatch:stream")},function(o,n){o&&(u=e.concat(u),"InvalidSequenceTokenException"==o.code&&localStorage.setItem("ConsoleCloudWatch:sequenceToken",o.message.split("The next expected sequenceToken is: ")[1])),n&&localStorage.setItem("ConsoleCloudWatch:sequenceToken",n.nextSequenceToken)})},r||1e4))})}var u=[],i=new AWS.CloudWatchLogs({accessKeyId:e,secretAccessKey:o,region:n}),l=localStorage.getItem("ConsoleCloudWatch:stream");l?a(l):"undefined"==typeof Fingerprint2?a(function(){function e(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()}()):(new Fingerprint2).get(function(e,o){a(e)}),window.onerror=function(e,o,n,t,c){StackTrace.fromError(c).then(function(c){var r=e+"\n"+o+":"+n+":"+t+"\n"+c.map(function(e){return e.toString()}).join("\n");u.push({message:r,timestamp:(new Date).getTime()})})},"undefined"!=typeof console&&(c||["error"]).forEach(function(e){var o=console[e];console[e]=function(e){u.push({message:e,timestamp:(new Date).getTime()}),s||o(e)}})}}); -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Console Cloud Watch 2 | 3 | Send your browser errors and console message to AWS CLoudWatch 4 | 5 | ## Setup 6 | 7 | - Login to AWS console 8 | - Open CloudWatch 9 | - Create a Log Group (Set up a retention period to save space) 10 | - Open IAM 11 | - Create a new user with secret and access key 12 | - Assign the user a new policy wich will be able to write logs and create log streams (set your region and log group name): 13 | ```json 14 | { 15 | "Version": "2012-10-17", 16 | "Statement": [ 17 | { 18 | "Sid": "VisualEditor0", 19 | "Effect": "Allow", 20 | "Action": [ 21 | "logs:CreateLogStream", 22 | "logs:PutLogEvents" 23 | ], 24 | "Resource": [ 25 | "arn:aws:logs:AWS_REGION:*:log-group:LOG_GROUP:*:*", 26 | "arn:aws:logs:AWS_REGION:*:log-group:LOG_GROUP" 27 | ] 28 | } 29 | ] 30 | } 31 | ``` 32 | - beware that the credentials will be exposed in the browser so don't assign other permissions to this user. 33 | 34 | ## Get Console Cloud Watch 35 | 36 | npm: 37 | ``` 38 | npm install console-cloud-watch 39 | ``` 40 | CDN: 41 | ```html 42 | 43 | ``` 44 | `dist/console-cloud-watch-all.min.js` contains all the dependencies (and a custom build of AWS SDK with only the CloudWatch service), 45 | if you already include AWS SDK you may use `dist/dist/console-cloud-watch.min.js` directly, note that you have also to include `fingerprintjs2` and `stacktrace-js` 46 | 47 | 48 | 49 | ## Usage 50 | Include `console-cloud-watch.js` in your page, configure your parameters and you are done. Make sure that AWS, StackTrace, and optionally Fingerprint2 have been required as well: 51 | 52 | ```javascript 53 | # ES6 54 | import ConsoleCloudWatch from 'console-cloud-watch'; 55 | # ES5 56 | var ConsoleCloudWatch = require('console-cloud-watch'); 57 | 58 | 59 | ConsoleCloudWatch(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION, LOG_GROUP); 60 | ``` 61 | 62 | You may also pass 3 optional configuration parameters: 63 | 64 | - `levels` (default: `['error']`): an array of strings with the console levels to intercept 65 | - `timeout` (default: `10000`): milliseconds between calls to CloudWatch 66 | - `mute` (default: `false`): if set to `true`, intercepted message will not be shown in console 67 | 68 | Example: 69 | ```javascript 70 | ConsoleCloudWatch(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION, LOG_GROUP,['warn','error'],30000,true); 71 | ``` 72 | -------------------------------------------------------------------------------- /console-cloud-watch.js: -------------------------------------------------------------------------------- 1 | (function (name, context, definition) { 2 | 'use strict' 3 | if (typeof window.define === 'function' && window.define.amd) { window.define(definition) } else if (typeof module !== 'undefined' && module.exports) { module.exports = definition() } else if (context.exports) { context.exports = definition() } else { context[name] = definition() } 4 | })('ConsoleCloudWatch', this, function () { 5 | 6 | return function (aws_access_key_id, aws_secret_access_key, region, group, levels, timeout, mute) { 7 | var logEvents = []; 8 | var cloudwatchlogs = new AWS.CloudWatchLogs({ 9 | accessKeyId: aws_access_key_id, secretAccessKey: aws_secret_access_key, region: region 10 | }); 11 | 12 | var stream = localStorage.getItem('ConsoleCloudWatch:stream'); 13 | 14 | if (stream) { 15 | createStream(stream); 16 | } else { 17 | if (typeof (Fingerprint2) == 'undefined') { 18 | function guid() { 19 | function s4() { 20 | return Math.floor((1 + Math.random()) * 0x10000) 21 | .toString(16) 22 | .substring(1); 23 | } 24 | return s4() + s4() + '-' + s4() + '-' + s4() + '-' + 25 | s4() + '-' + s4() + s4() + s4(); 26 | } 27 | createStream(guid()); 28 | } else { 29 | new Fingerprint2().get(function (result, components) { 30 | createStream(result); 31 | }); 32 | } 33 | } 34 | window.onerror = function (msg, file, line, col, error) { 35 | StackTrace.fromError(error).then(function (stackFrames) { 36 | var stringifiedStack = msg + '\n' + file + ':' + line + ':' + col + '\n' + stackFrames.map(function (sf) { 37 | return sf.toString(); 38 | }).join('\n'); 39 | logEvents.push({ 40 | message: stringifiedStack, 41 | timestamp: new Date().getTime() 42 | }); 43 | }); 44 | }; 45 | 46 | if (typeof (console) !== 'undefined') { 47 | (levels || ['error']).forEach(function (level) { 48 | var originalFn = console[level]; 49 | console[level] = function (msg) { 50 | logEvents.push({ 51 | message: msg, 52 | timestamp: new Date().getTime() 53 | }); 54 | if (!mute) { 55 | originalFn(msg); 56 | } 57 | } 58 | }); 59 | } 60 | 61 | function init() { 62 | setInterval(function () { 63 | var pendingEvents = logEvents.splice(0); 64 | if (pendingEvents.length) { 65 | cloudwatchlogs.putLogEvents({ 66 | logEvents: pendingEvents, 67 | sequenceToken: localStorage.getItem('ConsoleCloudWatch:sequenceToken'), 68 | logGroupName: group, 69 | logStreamName: localStorage.getItem('ConsoleCloudWatch:stream') 70 | }, function (err, data) { 71 | if (err) { 72 | logEvents = pendingEvents.concat(logEvents); 73 | if (err.code == "InvalidSequenceTokenException") { 74 | localStorage.setItem('ConsoleCloudWatch:sequenceToken', err.message.split('The next expected sequenceToken is: ')[1]) 75 | } 76 | } 77 | if (data) { 78 | localStorage.setItem('ConsoleCloudWatch:sequenceToken', data.nextSequenceToken) 79 | } 80 | }); 81 | } 82 | }, timeout || 10000); 83 | } 84 | 85 | function createStream(stream) { 86 | cloudwatchlogs.createLogStream({ 87 | logGroupName: group, 88 | logStreamName: stream 89 | }, function (err, data) { 90 | if (err && err.code !== 'ResourceAlreadyExistsException') { 91 | console.log(err, err.stack); 92 | } else { 93 | localStorage.setItem('ConsoleCloudWatch:stream', stream); 94 | init(); 95 | } 96 | }); 97 | } 98 | }; 99 | }); --------------------------------------------------------------------------------