Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

timer-logs

Package Overview
Dependencies
Maintainers
1
Versions
22
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

timer-logs - npm Package Compare versions

Comparing version 1.3.1 to 1.4.0

logPresenter.d.ts

9

exemplar/index.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const index_1 = require("../index");
const timer = new index_1.default({ filename: '/exemplar/index.ts', label: 'Examplary!', omitStackTrace: true });
const timer = new index_1.default({ filename: '/exemplar/index.ts', label: 'Exemplary!', omitStackTrace: true });
timer.customError('Hellp!');

@@ -14,3 +14,3 @@ try {

.then(() => {
throw new Error('Unexpected error occured');
throw new Error('Unexpected error occurred');
}).catch(timer.genericErrorCustomMessage('A better explanation for what caused this error'));

@@ -20,3 +20,3 @@ const postgresExample = async () => {

.then(() => {
throw new Error('Unexpected error occured');
throw new Error('Unexpected error occurred');
return { rows: ['row1', 'row2'] };

@@ -28,3 +28,6 @@ })

postgresExample().then(() => {
timer.info('Some information about the current state of the program:', false, 1, 2, 3, ['one', 'two', 'three']);
timer.alert('Something has gone seriously wrong!');
timer.warn('This shouldn\'t happen under normal circumstances, but isn\'t a catastrophe');
timer.flush();
});
import Timer from '../index'
// instantiate the logger with some config values. The bare minimum is the filename
const timer = new Timer({filename: '/exemplar/index.ts', label: 'Examplary!', omitStackTrace: true})
const timer = new Timer({filename: '/exemplar/index.ts', label: 'Exemplary!', omitStackTrace: true})

@@ -19,3 +19,3 @@ // log a custom error without actually throwing Error

.then(()=> {
throw new Error('Unexpected error occured')
throw new Error('Unexpected error occurred')
}).catch(timer.genericErrorCustomMessage('A better explanation for what caused this error'))

@@ -26,3 +26,3 @@

.then(()=> {
throw new Error('Unexpected error occured')
throw new Error('Unexpected error occurred')
return {rows: ['row1', 'row2']}

@@ -34,4 +34,8 @@ })

postgresExample().then(()=>{
timer.info('Some information about the current state of the program:', false, 1, 2, 3, ['one', 'two', 'three'])
timer.alert('Something has gone seriously wrong!')
timer.warn('This shouldn\'t happen under normal circumstances, but isn\'t a catastrophe')
// always call flush at the end of the file (before the return statement) to print out the log
timer.flush()
})

@@ -1,2 +0,5 @@

declare type Config = {
declare type LogDetails = {
[key: string]: string | number | boolean;
};
interface Config {
/**

@@ -13,5 +16,3 @@ * the severity of the log, defaults to DEFAULT

*/
details?: {
[key: string]: string | number;
};
details?: LogDetails;
/** filename of the typescript source file where the log is coming from */

@@ -34,4 +35,4 @@ filename: string;

omitStackTrace?: boolean;
};
declare enum Severity {
}
export declare enum Severity {
DEFAULT = "DEFAULT",

@@ -51,6 +52,11 @@ DEBUG = "DEBUG",

private mostRecentlyStartedLabel?;
private config;
private readonly savedTimes;
private splitFilePath;
private readonly splitFilePath;
private readonly filename;
private readonly uniqueId;
private readonly label;
private readonly details;
private readonly loggerName;
private readonly logClass;
private readonly omitStackTrace;
/**

@@ -64,2 +70,3 @@ * Create a new Timer object. Can have multiple timers within this object.

set severity(value: Severity);
private static consoleLog;
/**

@@ -121,2 +128,14 @@ * Start a new timer

/**
* Log a message at INFO severity level.
*/
info(message: string, ...messages: any[]): void;
/**
* Log a message at WARNING severity level.
*/
warn(message: string, ...messages: any[]): void;
/**
* Log a message at ALERT severity level.
*/
alert(message: string, ...messages: any[]): void;
/**
* Logs a custom error message in a separate log to the main Timer

@@ -137,10 +156,2 @@ * @param message the string to log

/**
* Logs a postgres error and returns the value passed as the second parameter.
*
* @param e the postgres error object
* @param returnVal the value for this function to return after logging the error
* @private
*/
private _postgresError;
/**
* Convenience wrapper for postgresError, to return a value.

@@ -189,2 +200,10 @@ * By default it returns null, but can be overriden with this method.

/**
* Logs a postgres error and returns the value passed as the second parameter.
*
* @param e the postgres error object
* @param returnVal the value for this function to return after logging the error
* @private
*/
private _postgresError;
/**
* Internal printing method which makes sure all of the properties are printed with each log.

@@ -223,2 +242,14 @@ *

};
/**
* These are attributes that should be set on all log output, regardless of what triggered the log.
*/
export declare type GenericLog = {
severity: Severity;
filename: string;
logClass: string;
loggerName: string;
uniqueId: string;
timestamp: string;
[label: string]: string | number | boolean | null | undefined;
};
export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Severity = void 0;
const crypto = require("crypto");
const logPresenter_1 = require("./logPresenter");
var Severity;

@@ -15,19 +17,25 @@ (function (Severity) {

Severity["EMERGENCY"] = "EMERGENCY";
})(Severity || (Severity = {}));
})(Severity = exports.Severity || (exports.Severity = {}));
var Environment;
(function (Environment) {
Environment[Environment["DEVELOPMENT"] = 0] = "DEVELOPMENT";
Environment[Environment["BROWSER"] = 1] = "BROWSER";
Environment[Environment["PRODUCTION"] = 2] = "PRODUCTION";
})(Environment || (Environment = {}));
class Timer {
constructor(config) {
var _a, _b;
var _a, _b, _c, _d, _e, _f;
this.startTime = Date.now();
this.config = config;
this.config.details = (_a = config === null || config === void 0 ? void 0 : config.details) !== null && _a !== void 0 ? _a : {};
this.details = (_a = config.details) !== null && _a !== void 0 ? _a : {};
this.loggerName = (_b = config.loggerName) !== null && _b !== void 0 ? _b : 'timer-logs';
this.filename = config.filename;
this.splitFilePath = config.filename.split('/').filter(p => p.length > 0);
this.label = (_c = config.label) !== null && _c !== void 0 ? _c : this.splitFilePath.slice(-1)[0].split('.')[0];
this.savedTimes = {};
this._severity = Severity[(_b = this.config.severity) !== null && _b !== void 0 ? _b : Severity.DEFAULT];
if (this.config.label === undefined)
this.config.label = this.splitFilePath.slice(-1)[0].split('.')[0];
if (this.config.loggerName === undefined)
this.config.loggerName = 'timer-logs';
this.logClass = (_d = config.logClass) !== null && _d !== void 0 ? _d : this.splitFilePath.slice(-1)[0].split('.')[0];
this.omitStackTrace = (_e = config.omitStackTrace) !== null && _e !== void 0 ? _e : false;
this._severity = Severity[(_f = config.severity) !== null && _f !== void 0 ? _f : Severity.DEFAULT];
this.uniqueId = crypto.randomBytes(8).toString('hex');
this.start('operationTime');
this.start(this.config.label);
this.start(this.label);
}

@@ -37,2 +45,27 @@ set severity(value) {

}
static consoleLog(logObject) {
let environment;
if (typeof window !== 'undefined')
environment = Environment.BROWSER;
else if (process.env.NODE_ENV === 'development')
environment = Environment.DEVELOPMENT;
else
environment = Environment.PRODUCTION;
let logPresenter;
switch (environment) {
case Environment.BROWSER:
logPresenter = logPresenter_1.browserLogPresenter;
break;
case Environment.DEVELOPMENT:
logPresenter = logPresenter_1.developerLogPresenter;
break;
case Environment.PRODUCTION:
logPresenter = logPresenter_1.productionLogPresenter;
break;
default:
logPresenter = logPresenter_1.productionLogPresenter;
break;
}
logPresenter(logObject);
}
start(label) {

@@ -77,3 +110,3 @@ console.assert(!this.savedTimes.hasOwnProperty(label), 'Timer started more than once for same label');

const printObject = {
message: this.config.label + `: ${this.finishTime - this.startTime}ms`
message: this.label + `: ${this.finishTime - this.startTime}ms`
};

@@ -86,4 +119,4 @@ const printMap = new Map(Object.entries(printObject));

});
if (this.config.details)
Object.entries(this.config.details).forEach(([label, detail]) => {
if (this.details)
Object.entries(this.details).forEach(([label, detail]) => {
printMap.set(label, detail);

@@ -95,8 +128,6 @@ });

addDetail(key, value = true) {
var _a;
Object.assign((_a = this.config) === null || _a === void 0 ? void 0 : _a.details, { [key]: value });
Object.assign(this.details, { [key]: value });
}
addDetails(details) {
var _a;
Object.assign((_a = this.config) === null || _a === void 0 ? void 0 : _a.details, details);
Object.assign(this.details, details);
}

@@ -106,2 +137,20 @@ getTimeUntilNow() {

}
info(message, ...messages) {
const concatenatedMessage = [message].concat(messages === null || messages === void 0 ? void 0 : messages.map(m => m.toString())).join(' ');
this.printLog(new Map([
['message', concatenatedMessage],
]), Severity.INFO);
}
warn(message, ...messages) {
const concatenatedMessage = [message].concat(messages === null || messages === void 0 ? void 0 : messages.map(m => m.toString())).join(' ');
this.printLog(new Map([
['message', concatenatedMessage],
]), Severity.WARNING);
}
alert(message, ...messages) {
const concatenatedMessage = [message].concat(messages === null || messages === void 0 ? void 0 : messages.map(m => m.toString())).join(' ');
this.printLog(new Map([
['message', concatenatedMessage],
]), Severity.ALERT);
}
customError(message) {

@@ -114,10 +163,2 @@ const errorDetails = new Map(Object.entries({ message }));

}
_postgresError(e, returnVal) {
const errorDetails = new Map(Object.entries(e));
if (!errorDetails.has('message'))
errorDetails.set('message', 'Postgres error code ' + e.code);
errorDetails.set("databaseType", "postgres");
this.printLog(errorDetails, Severity.ERROR);
return returnVal;
}
postgresErrorReturn(returnValue) {

@@ -130,3 +171,3 @@ return (e) => this._postgresError(e, returnValue);

]);
if (!this.config.omitStackTrace && e.stack)
if (!this.omitStackTrace && e.stack)
errorDetails.set('stackTrace', e.stack);

@@ -144,12 +185,20 @@ if (message) {

}
_postgresError(e, returnVal) {
const errorDetails = new Map(Object.entries(e));
if (!errorDetails.has('message'))
errorDetails.set('message', 'Postgres error code ' + e.code);
errorDetails.set("databaseType", "postgres");
this.printLog(errorDetails, Severity.ERROR);
return returnVal;
}
printLog(details, severity) {
var _a;
if (!details.has('message')) {
details.set('message', 'timer-logs unset message in file ' + this.config.filename);
details.set('message', 'timer-logs unset message in file ' + this.filename);
}
const log = {
severity: severity,
filename: this.config.filename,
logClass: (_a = this.config.logClass) !== null && _a !== void 0 ? _a : this.splitFilePath.slice(-1)[0].split('.')[0],
loggerName: this.config.loggerName,
filename: this.filename,
logClass: (_a = this.logClass) !== null && _a !== void 0 ? _a : this.splitFilePath.slice(-1)[0].split('.')[0],
loggerName: this.loggerName,
uniqueId: this.uniqueId,

@@ -164,28 +213,5 @@ timestamp: new Date().toUTCString(),

});
const logString = JSON.stringify(log);
switch (severity) {
case Severity.DEBUG:
console.debug(logString);
break;
case Severity.DEFAULT:
console.log(logString);
break;
case Severity.INFO:
case Severity.NOTICE:
console.info(logString);
break;
case Severity.WARNING:
console.warn(logString);
break;
case Severity.ERROR:
case Severity.CRITICAL:
case Severity.ALERT:
case Severity.EMERGENCY:
console.error(logString);
break;
default:
console.log(logString);
}
Timer.consoleLog(log);
}
}
exports.default = Timer;
import * as crypto from 'crypto'
import {browserLogPresenter, developerLogPresenter, productionLogPresenter} from "./logPresenter";
type Config = {
type LogDetails = { [key: string]: string | number | boolean }
interface Config {
/**

@@ -15,3 +18,3 @@ * the severity of the log, defaults to DEFAULT

*/
details?: { [key: string]: string | number }
details?: LogDetails
/** filename of the typescript source file where the log is coming from */

@@ -36,3 +39,16 @@ filename: string

enum Severity {
/**
* The same options that can be passed in, but not optional. By this point the default will be set if not passed in.
*/
interface InternalConfig extends Config {
severity: Severity
label: string
details: LogDetails
filename: string
loggerName: string
logClass: string
omitStackTrace: boolean
}
export enum Severity {
DEFAULT = "DEFAULT",

@@ -49,2 +65,8 @@ DEBUG = "DEBUG",

enum Environment {
DEVELOPMENT,
BROWSER,
PRODUCTION
}
export default class Timer {

@@ -54,6 +76,11 @@ private readonly startTime: number

private mostRecentlyStartedLabel?: string
private config: Config
private readonly savedTimes: { [label: string]: { startTime: number; finishTime?: number; time?: number } }
private splitFilePath: string[]
private readonly splitFilePath: string[]
private readonly filename: string
private readonly uniqueId: string
private readonly label: string
private readonly details: LogDetails
private readonly loggerName: string
private readonly logClass: string
private readonly omitStackTrace: boolean

@@ -67,12 +94,14 @@ /**

this.startTime = Date.now()
this.config = config
this.config.details = config?.details ?? {}
this.details = config.details ?? {}
this.loggerName = config.loggerName ?? 'timer-logs'
this.filename = config.filename
this.splitFilePath = config.filename.split('/').filter(p => p.length > 0)
this.label = config.label ?? this.splitFilePath.slice(-1)[0].split('.')[0]
this.savedTimes = {}
this._severity = Severity[this.config.severity ?? Severity.DEFAULT]
if (this.config.label === undefined) this.config.label = this.splitFilePath.slice(-1)[0].split('.')[0]
if(this.config.loggerName === undefined) this.config.loggerName = 'timer-logs'
this.logClass = config.logClass ?? this.splitFilePath.slice(-1)[0].split('.')[0]
this.omitStackTrace = config.omitStackTrace ?? false
this._severity = Severity[config.severity ?? Severity.DEFAULT]
this.uniqueId = crypto.randomBytes(8).toString('hex')
this.start('operationTime')
this.start(this.config.label)
this.start(this.label)
}

@@ -86,2 +115,29 @@

private static consoleLog(logObject: GenericLog) {
let environment: Environment
if (typeof window !== 'undefined')
environment = Environment.BROWSER
else if (process.env.NODE_ENV === 'development')
environment = Environment.DEVELOPMENT
else
environment = Environment.PRODUCTION
let logPresenter: (logObject: GenericLog) => void
switch (environment) {
case Environment.BROWSER:
logPresenter = browserLogPresenter
break;
case Environment.DEVELOPMENT:
logPresenter = developerLogPresenter
break;
case Environment.PRODUCTION:
logPresenter = productionLogPresenter
break;
default:
logPresenter = productionLogPresenter
break
}
logPresenter(logObject)
}
/**

@@ -159,4 +215,4 @@ * Start a new timer

if (this.mostRecentlyStartedLabel && !this.savedTimes[this.mostRecentlyStartedLabel].finishTime) this.end()
const printObject: { [label: string]: string | number } = {
message: this.config.label + `: ${this.finishTime - this.startTime}ms`
const printObject: { [label: string]: string | number | boolean } = {
message: this.label + `: ${this.finishTime - this.startTime}ms`
}

@@ -168,4 +224,4 @@ const printMap = new Map(Object.entries(printObject))

})
if (this.config.details)
Object.entries(this.config.details).forEach(([label, detail]) => {
if (this.details)
Object.entries(this.details).forEach(([label, detail]) => {
printMap.set(label, detail)

@@ -184,3 +240,3 @@ })

public addDetail(key: string, value: string | number | boolean = true) {
Object.assign(this.config?.details, {[key]: value})
Object.assign(this.details, {[key]: value})
}

@@ -194,3 +250,3 @@

public addDetails(details: { [key: string]: string | number | boolean }) {
Object.assign(this.config?.details, details)
Object.assign(this.details, details)
}

@@ -206,2 +262,32 @@

/**
* Log a message at INFO severity level.
*/
public info(message: string, ...messages: any[]) {
const concatenatedMessage = [message].concat(messages?.map(m => m.toString())).join(' ')
this.printLog(new Map([
['message', concatenatedMessage],
]), Severity.INFO)
}
/**
* Log a message at WARNING severity level.
*/
public warn(message: string, ...messages: any[]) {
const concatenatedMessage = [message].concat(messages?.map(m => m.toString())).join(' ')
this.printLog(new Map([
['message', concatenatedMessage],
]), Severity.WARNING)
}
/**
* Log a message at ALERT severity level.
*/
public alert(message: string, ...messages: any[]) {
const concatenatedMessage = [message].concat(messages?.map(m => m.toString())).join(' ')
this.printLog(new Map([
['message', concatenatedMessage],
]), Severity.ALERT)
}
/**
* Logs a custom error message in a separate log to the main Timer

@@ -224,3 +310,3 @@ * @param message the string to log

*/
public postgresError(e: PostgresError): null{
public postgresError(e: PostgresError): null {
return this._postgresError(e, null)

@@ -230,17 +316,2 @@ }

/**
* Logs a postgres error and returns the value passed as the second parameter.
*
* @param e the postgres error object
* @param returnVal the value for this function to return after logging the error
* @private
*/
private _postgresError<ReturnType>(e: PostgresError, returnVal: ReturnType): ReturnType {
const errorDetails = new Map(Object.entries(e))
if(!errorDetails.has('message')) errorDetails.set('message', 'Postgres error code '+e.code)
errorDetails.set("databaseType", "postgres")
this.printLog(errorDetails, Severity.ERROR)
return returnVal
}
/**
* Convenience wrapper for postgresError, to return a value.

@@ -280,3 +351,3 @@ * By default it returns null, but can be overriden with this method.

])
if (!this.config.omitStackTrace && e.stack) errorDetails.set('stackTrace', e.stack)
if (!this.omitStackTrace && e.stack) errorDetails.set('stackTrace', e.stack)
if (message) {

@@ -307,2 +378,17 @@ errorDetails.set('message', message)

/**
* Logs a postgres error and returns the value passed as the second parameter.
*
* @param e the postgres error object
* @param returnVal the value for this function to return after logging the error
* @private
*/
private _postgresError<ReturnType>(e: PostgresError, returnVal: ReturnType): ReturnType {
const errorDetails = new Map(Object.entries(e))
if (!errorDetails.has('message')) errorDetails.set('message', 'Postgres error code ' + e.code)
errorDetails.set("databaseType", "postgres")
this.printLog(errorDetails, Severity.ERROR)
return returnVal
}
/**
* Internal printing method which makes sure all of the properties are printed with each log.

@@ -315,11 +401,11 @@ *

private printLog(details: Map<string, string | number | boolean | null | undefined>, severity: Severity) {
if(!details.has('message')){
if (!details.has('message')) {
// this should never be triggered. Always pass a message in the details map. Just a backup:
details.set('message', 'timer-logs unset message in file '+this.config.filename)
details.set('message', 'timer-logs unset message in file ' + this.filename)
}
const log: { [label: string]: string | number | boolean | null | undefined } = {
const log: GenericLog = {
severity: severity,
filename: this.config.filename,
logClass: this.config.logClass ?? this.splitFilePath.slice(-1)[0].split('.')[0],
loggerName: this.config.loggerName,
filename: this.filename,
logClass: this.logClass ?? this.splitFilePath.slice(-1)[0].split('.')[0],
loggerName: this.loggerName,
uniqueId: this.uniqueId,

@@ -334,27 +420,3 @@ timestamp: new Date().toUTCString(),

})
const logString: string = JSON.stringify(log)
// this affects how logs are printed in the browser
switch (severity) {
case Severity.DEBUG:
console.debug(logString)
break;
case Severity.DEFAULT:
console.log(logString)
break;
case Severity.INFO:
case Severity.NOTICE:
console.info(logString)
break;
case Severity.WARNING:
console.warn(logString)
break;
case Severity.ERROR:
case Severity.CRITICAL:
case Severity.ALERT:
case Severity.EMERGENCY:
console.error(logString)
break;
default:
console.log(logString)
}
Timer.consoleLog(log)
}

@@ -388,1 +450,13 @@ }

/**
* These are attributes that should be set on all log output, regardless of what triggered the log.
*/
export type GenericLog = {
severity: Severity,
filename: string,
logClass: string,
loggerName: string,
uniqueId: string,
timestamp: string,
[label: string]: string | number | boolean | null | undefined
}
{
"name": "timer-logs",
"version": "1.3.1",
"version": "1.4.0",
"devDependencies": {

@@ -5,0 +5,0 @@ "@types/node": "^15.00.0"

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