UNPKG

monitor-nodejs

Version:
145 lines (114 loc) 3.04 kB
'use strict' const os = require('os') function detectIP() { // TODO: E.g. in PHP, gethostbyname(gethostname()); return '127.0.0.1' } function detectOS() { return process.platform } function Transaction(name) { this.model = 'transaction' this.name = name this.type = Transaction.TYPE_COMMON this.hash = `${Date.now()}${Math.floor(Math.random() * 100)}` this.host = { hostname: os.hostname(), ip: detectIP(), os: detectOS(), } this.result = Transaction.RESULT_SUCCESS this.timestamp = undefined this.duration = undefined this.memory_peak = undefined this.http = undefined this.user = undefined this.context = undefined this.start = (timestamp = null) => { this.timestamp = timestamp || (new Date().getTime() / 1000) return this } this.isStarted = () => { return this.timestamp !== undefined } this.end = (duration = null) => { this.memory_peak = parseFloat((process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)) this.duration = duration || parseFloat((new Date().getTime() / 1000 - this.timestamp).toFixed(2)) return this } this.isEnded = () => { return this.duration !== undefined } this.markAsCommon = () => { this.type = Transaction.TYPE_COMMON return this } this.markAsCommand = () => { this.type = Transaction.TYPE_COMMAND return this } this.markAsRequest = () => { this.type = Transaction.TYPE_REQUEST return this } this.markAsSuccess = () => { this.result = Transaction.RESULT_SUCCESS return this } this.markAsFailed = () => { this.result = Transaction.RESULT_FAILED return this } this.setType = (type) => { this.type = type return this } this.setHttp = (data) => { this.http = data } this.setUser = (id) => { this.user = { id } } this.addContext = (key, data) => { if (this.context === undefined) { this.context = {} } this.context[key] = data } this.transform = () => { const obj = { model: this.model, name: this.name, type: this.type, hash: this.hash, host: this.host, result: this.result, } if (this.timestamp) { obj['timestamp'] = this.timestamp } if (this.duration) { obj['duration'] = this.duration } if (this.memory_peak) { obj['memory_peak'] = this.memory_peak } if (this.context !== undefined) { obj['context'] = this.context } if (this.http !== undefined) { obj['http'] = this.http } if (this.user !== undefined) { obj['user'] = this.user } return obj } } Transaction.TYPE_COMMON = 'common' Transaction.TYPE_COMMAND = 'command' Transaction.TYPE_REQUEST = 'request' Transaction.TYPE_UNEXPECTED = 'unexpected' Transaction.RESULT_SUCCESS = 'success' Transaction.RESULT_FAILED = 'failed' module.exports = Transaction