All files / Nodejs/lib logging.js

12.82% Statements 10/78
0% Branches 0/16
0% Functions 0/18
12.82% Lines 10/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 1701x 1x 1x 1x 1x 1x 1x   1x   1x                                                                                                                                                                                                                                                                                                                           1x  
var os = require("os");
var path = require("path");
var fs = require("fs");
var AWS = require("./leo-aws");
var https = require("https");
var moment = require("moment");
var uuid = require("uuid");
 
const accessor = {};
 
module.exports = function (id, opts) {
 
	opts = Object.assign({
		version: 'latest'
	}, opts);
	var startTime = Date.now();
 
 
	//console.log(opts);
	var client = new AWS.CloudWatchLogs({
		region: opts.aws.region,
		httpOptions: {
			agent: new https.Agent({
				ciphers: 'ALL',
				secureProtocol: 'TLSv1_method',
				keepAlive: true
			})
		},
		credentials: opts.credentials
	});
 
	var configFile = path.resolve(os.tmpdir(), `leolog_${id.toString()}.json`);
	var config = null;
 
 
	var logGroupName = `/aws/lambda/${id}`;
 
	var requestId = uuid.v1();
 
	function addMessage(message) {
		if (message == "\n") {
			return;
		}
		logs.push({
			timestamp: Date.now(),
			message: moment().toISOString() + `	${requestId}	${message}`
		});
	}
 
	var oldStdOut = process.stdout.write;
	var oldStdErr = process.stderr.write;
	process.stdout.write = function (string, encoding, fd) {
		oldStdOut.apply(process.stdout, arguments);
		addMessage(string);
	};
 
	process.stderr.write = function (string, encoding, fd) {
		oldStdErr.apply(process.stderr, arguments);
		addMessage(string);
	};
 
 
 
	var logs = [];
	addMessage(`START RequestId: ${requestId} Version: ${opts.version}`);
 
	function createLogStream(callback) {
		var logStreamName = moment().format("YYYY/MM/DD/") + `${opts.version}/${os.hostname()}/` + Date.now();
		client.createLogGroup({
			logGroupName: logGroupName
		}, (err, data) => {
			if (err && err.code != "ResourceAlreadyExistsException") {
				callback(err);
			} else {
				config = {
					logGroupName: logGroupName,
					logStreamName: logStreamName
				};
				client.createLogStream(config, (err, data) => {
					config.sequenceNumber = undefined;
					fs.writeFile(configFile, JSON.stringify(config, null, 2), (err, data) => {
						callback(err, config);
					});
				});
			}
		});
	}
 
	function getLogStream(callback) {
		if (config) {
			callback(null, config);
		} else {
			fs.exists(configFile, (exists) => {
				console.log(exists);
				if (!exists) {
					console.log("creating log stream", configFile);
					createLogStream(callback);
				} else {
					console.log("reading log stream", configFile);
					fs.readFile(configFile, (err, data) => {
						config = JSON.parse(data);
						callback(err, config);
					});
				}
			});
		}
	}
 
	function sendEvents(callback) {
		console.log("sending events");
		getLogStream((err, config) => {
			console.log(config);
			if (err) {
				callback(err);
			} else {
				client.putLogEvents({
					logEvents: logs.slice(0),
					logGroupName: config.logGroupName,
					logStreamName: config.logStreamName,
					sequenceToken: config.sequenceNumber
				}, (err, data) => {
					console.log(err, data);
					if (err) {
						callback(err);
					} else {
						console.log(data);
						config.sequenceNumber = data.nextSequenceToken;
						fs.writeFile(configFile, JSON.stringify(config, null, 2), callback);
					}
				});
				logs = [];
			}
 
		});
	}
 
	var logger = {
		sendEvents,
		end: function (callback) {
			process.stdout.write = oldStdOut;
			process.stderr.write = oldStdErr;
 
			var memory = (process.memoryUsage().heapTotal / 1024 / 1024).toFixed(0);
 
			addMessage(`REPORT RequestId: ${requestId}	Duration: ${Date.now() - startTime} ms	Billed Duration: 0 ms Memory Size: ${memory} MB	Max Memory Used: ${memory} MB`);
 
			sendEvents(callback);
 
		}
	};
 
	process.once("beforeExit", () => {
		logger.end((err) => {
			if (err) {
				console.log("Error uploading logs to aws:", err);
			}
			console.log("Finished uploading logs", config.logGroupName);
		});
	});
	process.on("uncaughtException", (err) => {
		// "beforeExit" is not called on uncaught exceptions
		// By catching and logging the error it adds to the event loop and causes "beforeExit" to fire
		console.error(err);
	});
	accessor.logger = logger;
	return logger;
};
 
module.exports.accessor = accessor;