New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

syncano-server

Package Overview
Dependencies
Maintainers
2
Versions
99
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

syncano-server - npm Package Compare versions

Comparing version 0.7.2-33 to 0.7.2-34

.nyc_output/1320c49aa5ee6c5ab93027587988436a.json

182

lib/logger.js

@@ -7,48 +7,40 @@ 'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
* Debug your code.
* @property {Function}
*/
var _chalk = require('chalk');
var _chalk2 = _interopRequireDefault(_chalk);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Debug your code.
* @property {Function}
*/
var TYPES = {
emergency: 'Emergency',
alert: 'Alert',
critical: 'Critical',
error: 'Error',
warning: 'Warning',
notice: 'Notice',
info: 'Info',
debug: 'Debug'
var LEVELS = ['error', 'warn', 'info', 'debug'];
var COLORS = {
error: 'red',
warn: 'yellow',
info: 'gray',
debug: 'blue'
};
var Logger = function () {
function Logger() {
function Logger(_ref) {
var _this = this;
var scope = _ref.scope,
callback = _ref.callback,
levels = _ref.levels;
_classCallCheck(this, Logger);
this._start = null;
this._callback = null;
this._scope = scope;
this._callback = callback;
Object.keys(TYPES).forEach(function (level) {
_this[level] = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this._level = TYPES[level];
var date = _this._print.apply(_this, args);
if (_this._callback) {
_this._callback({ args: args, date: date, level: level });
}
_this._level = null;
return _this;
};
levels.forEach(function (level) {
_this[level] = _this._makePrinter.bind(_this, level);
});

@@ -58,24 +50,23 @@ }

_createClass(Logger, [{
key: 'log',
value: function log() {
if (!this._start) {
this._start = this._getNow();
key: '_makePrinter',
value: function _makePrinter() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (arguments.length > 0) {
this._print.apply(this, arguments);
this._start = this._start || this._getNow();
this._level = args.shift();
var date = this._print.apply(this, args);
if (this._callback) {
this._callback({ args: args, date: date, level: this._level });
}
return this;
this._level = null;
}
}, {
key: 'listen',
value: function listen(callback) {
if (typeof callback !== 'function') {
throw new Error('Callback must be a function.');
}
this._callback = callback;
return this;
key: '_pad',
value: function _pad(width, string, padding) {
return width <= string.length ? string : this._pad(width, string + padding, padding);
}

@@ -89,23 +80,60 @@ }, {

var color = COLORS[this._level];
// Time
var now = this._getNow();
var diff = _chalk2.default[color]('+' + this._calculateDiff(this._start, now));
var time = _chalk2.default.gray(this._getNowString(now).split(' ')[1]);
if (!this._shouldLog(this._scope)) {
return;
}
// Level
var levelName = this._pad(5, '' + this._level, ' ');
var level = color ? _chalk2.default[color](levelName) : levelName;
args = args.map(this._parseArg).join(' ');
console.log(level, this._scope, time, diff, args);
return now;
}
}, {
key: '_shouldLog',
value: function _shouldLog(scope) {
if (global.ARGS && global.ARGS.DEBUG) {
var now = this._getNow();
var diff = this._calculateDiff(this._start, now);
var level = null;
if (typeof global.ARGS.DEBUG === 'boolean') {
return global.ARGS.DEBUG;
}
args = args.map(function (arg) {
return arg instanceof Object && arg !== null ? JSON.stringify(arg) : arg;
var vars = global.ARGS.DEBUG.split(',');
var excluded = vars.filter(function (item) {
return (/^-/.test(item)
);
}).map(function (item) {
return item.replace(/^-/, '');
});
if (this._level !== null) {
level = this._level + ':';
}
var matchAll = vars.filter(function (item) {
return item === '*';
}).length;
var isWhitelisted = vars.indexOf(scope) >= 0;
var isExcluded = excluded.indexOf(scope) >= 0;
if (level) {
console.log(level, this._getNowString(now), args.join(' '), '+' + diff);
} else {
console.log(this._getNowString(now), args.join(' '), '+' + diff);
}
return (matchAll || isWhitelisted) && !isExcluded;
}
return now;
return false;
}
}, {
key: '_parseArg',
value: function _parseArg(arg) {
var isObject = arg instanceof Object && arg !== null;
if (isObject) {
return '\n\n ' + JSON.stringify(arg, null, 2).split('\n').join('\n ') + '\n';
}
return arg;
}

@@ -133,4 +161,26 @@ }, {

var logger = new Logger();
var logger = function logger(scope) {
return new Logger({
scope: scope,
callback: logger._callback,
levels: logger._levels || LEVELS
});
};
exports.default = logger.log.bind(logger);
logger.levels = function (levels) {
if (!Array.isArray(levels)) {
throw new Error('Levels must be array of strings.');
}
logger._levels = levels;
};
logger.listen = function (callback) {
if (typeof callback !== 'function') {
throw new Error('Callback must be a function.');
}
logger._callback = callback;
};
exports.default = logger;

@@ -43,3 +43,3 @@ 'use strict';

var isLocal = !global.setResponse || !global.HttpResponse;
var args = [this._content, this._status, this._mimetype, this._headers];
var args = [this._status, this._content, this._mimetype, this._headers];

@@ -46,0 +46,0 @@ if (isLocal) {

{
"name": "syncano-server",
"version": "0.7.2-33",
"version": "0.7.2-34",
"description": "A library to intereact with the Syncano API on a server side",

@@ -42,2 +42,3 @@ "main": "lib/index.js",

"dependencies": {
"chalk": "^1.1.3",
"node-fetch": "2.0.0-alpha.3"

@@ -44,0 +45,0 @@ },

@@ -140,27 +140,31 @@ [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo) [![CircleCI](https://circleci.com/gh/Syncano/syncano-server-js/tree/devel.svg?style=shield&circle-token=0340c11444db6f3dc227cf310f4d8ff1bd90dee8)](https://circleci.com/gh/Syncano/syncano-server-js/tree/devel)

The logger provides the eight logging levels defined in [RFC 5424](https://tools.ietf.org/html/rfc5424): emergency, alert, critical, error, warning, notice, info and debug.
The DEBUG environment variable is used to enable logging.
On Windows:
```
set DEBUG=*,-not_this
```
```js
import {logger} from 'syncano-server'
// Basic logger
logger('Message without logging level')
logger({hello: 'World'}, 'Hello world object')
// Listen for all events
logger.listen(event => {
// Handle event - save to db or send email
})
// Create custom logger levels - optionally
// Defaults are: error, warn, debug, info
logger.levels(['error', 'notice', 'fatal'])
// Initialize logger with scope "User Socket"
const log = logger('User Socket')
// Specific level loggers
logger().emergency('This is emergency message!')
logger().alert('This is alert message!')
logger().critical('This is critical message!')
logger().error('This is error message!')
logger().warning('This is warning message!')
logger().notice('This is notice message!')
logger().info('This is info message!')
logger().debug('This is debug message!')
// Listening on logged messages
logger().listen(event => {
// Handle event
})
log.error('This is error message!')
log.warn('This is warning message!')
log.info('This is info message!', {hello: "world"})
log.debug('This is debug message!')
```
Check [documentation](http://syncano.github.io/syncano-server-js/) to learn more.

@@ -5,79 +5,92 @@ /**

*/
import chalk from 'chalk'
const TYPES = {
emergency: 'Emergency',
alert: 'Alert',
critical: 'Critical',
error: 'Error',
warning: 'Warning',
notice: 'Notice',
info: 'Info',
debug: 'Debug'
const LEVELS = ['error', 'warn', 'info', 'debug']
const COLORS = {
error: 'red',
warn: 'yellow',
info: 'gray',
debug: 'blue'
}
class Logger {
constructor() {
constructor({scope, callback, levels}) {
this._start = null
this._callback = null
this._scope = scope
this._callback = callback
Object.keys(TYPES).forEach(level => {
this[level] = (...args) => {
this._level = TYPES[level]
const date = this._print(...args)
if (this._callback) {
this._callback({args, date, level})
}
this._level = null
return this
}
levels.forEach(level => {
this[level] = this._makePrinter.bind(this, level)
})
}
log(...args) {
if (!this._start) {
this._start = this._getNow()
}
_makePrinter(...args) {
this._start = this._start || this._getNow()
this._level = args.shift()
if (args.length > 0) {
this._print(...args)
const date = this._print(...args)
if (this._callback) {
this._callback({args, date, level: this._level})
}
return this
this._level = null
}
listen(callback) {
if (typeof callback !== 'function') {
throw new Error('Callback must be a function.')
_pad(width, string, padding) {
return (width <= string.length) ? string : this._pad(width, string + padding, padding)
}
_print(...args) {
const color = COLORS[this._level]
// Time
const now = this._getNow()
const diff = chalk[color](`+${this._calculateDiff(this._start, now)}`)
const time = chalk.gray(this._getNowString(now).split(' ')[1])
if (!this._shouldLog(this._scope)) {
return
}
this._callback = callback
// Level
const levelName = this._pad(5, `${this._level}`, ' ')
const level = color ? chalk[color](levelName) : levelName
return this
args = args.map(this._parseArg).join(' ')
console.log(level, this._scope, time, diff, args)
return now
}
_print(...args) {
_shouldLog(scope) {
if (global.ARGS && global.ARGS.DEBUG) {
const now = this._getNow()
const diff = this._calculateDiff(this._start, now)
let level = null
if (typeof global.ARGS.DEBUG === 'boolean') {
return global.ARGS.DEBUG
}
args = args.map(arg => {
return arg instanceof Object && arg !== null ? JSON.stringify(arg) : arg
})
const vars = global.ARGS.DEBUG.split(',')
const excluded = vars
.filter(item => /^-/.test(item))
.map(item => item.replace(/^-/, ''))
if (this._level !== null) {
level = `${this._level}:`
}
const matchAll = vars.filter(item => item === '*').length
const isWhitelisted = vars.indexOf(scope) >= 0
const isExcluded = excluded.indexOf(scope) >= 0
if (level) {
console.log(level, this._getNowString(now), args.join(' '), `+${diff}`)
} else {
console.log(this._getNowString(now), args.join(' '), `+${diff}`)
}
return (matchAll || isWhitelisted) && !isExcluded
}
return now
return false
}
_parseArg(arg) {
const isObject = arg instanceof Object && arg !== null
if (isObject) {
return `\n\n ${JSON.stringify(arg, null, 2).split('\n').join('\n ')}\n`
}
return arg
}

@@ -100,4 +113,26 @@

const logger = new Logger()
const logger = function (scope) {
return new Logger({
scope,
callback: logger._callback,
levels: logger._levels || LEVELS
})
}
export default logger.log.bind(logger)
logger.levels = function (levels) {
if (!Array.isArray(levels)) {
throw new Error('Levels must be array of strings.')
}
logger._levels = levels
}
logger.listen = function (callback) {
if (typeof callback !== 'function') {
throw new Error('Callback must be a function.')
}
logger._callback = callback
}
export default logger

@@ -20,3 +20,3 @@ /**

const isLocal = !global.setResponse || !global.HttpResponse
const args = [this._content, this._status, this._mimetype, this._headers]
const args = [this._status, this._content, this._mimetype, this._headers]

@@ -23,0 +23,0 @@ if (isLocal) {

@@ -5,10 +5,12 @@ import should from 'should/as-function'

describe('Logger', () => {
const {logger} = new Server({
token: 'testKey',
instanceName: 'testInstance'
})
let logger
let log = null
beforeEach(() => {
const server = new Server({
token: 'testKey',
instanceName: 'testInstance'
})
logger = server.logger
log = logger()

@@ -22,7 +24,7 @@ })

it('has _start property set to Date', () => {
should(log).have.property('_start').which.is.Date()
should(log).have.property('_start').which.is.null()
})
it('has _callback property set to Date', () => {
should(log).have.property('_callback').which.is.null()
it('has _callback property set to undefined', () => {
should(log).have.property('_callback').which.is.undefined()
})

@@ -32,23 +34,23 @@

it('should be a method of the model', () => {
should(log).have.property('listen').which.is.Function()
should(logger).have.property('listen').which.is.Function()
})
it('should throw when callback was not passed', () => {
should(log.listen).throw(/Callback must be a function./)
should(logger.listen).throw(/Callback must be a function./)
})
it('should save callback', () => {
should(log.listen(() => {})).have.property('_callback').which.is.Function()
logger.listen(() => {})
should(logger).have.property('_callback').which.is.Function()
})
})
describe('#alert()', () => {
describe('#levels()', () => {
it('should be a method of the model', () => {
should(log).have.property('alert').which.is.Function()
should(logger).have.property('levels').which.is.Function()
})
})
describe('#critical()', () => {
it('should be a method of the model', () => {
should(log).have.property('critical').which.is.Function()
it('should throw when array was not passed', () => {
should(logger.levels).throw(/Levels must be array of strings\./)
})

@@ -63,8 +65,2 @@ })

describe('#emergency()', () => {
it('should be a method of the model', () => {
should(log).have.property('emergency').which.is.Function()
})
})
describe('#error()', () => {

@@ -82,13 +78,7 @@ it('should be a method of the model', () => {

describe('#notice()', () => {
describe('#warn()', () => {
it('should be a method of the model', () => {
should(log).have.property('notice').which.is.Function()
should(log).have.property('warn').which.is.Function()
})
})
describe('#warning()', () => {
it('should be a method of the model', () => {
should(log).have.property('warning').which.is.Function()
})
})
})

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc