@voliware/logger
Advanced tools
Comparing version 2.0.4 to 2.0.5
@@ -1,1 +0,441 @@ | ||
class LoggerMessage{constructor({context:e=null,level:t=null,name:s=null,text:a="",timestamp:g=null}){this.context=e?`[${e}] `:"",this.level=null!==typeof t?`[${LoggerMessage.level.string[t]}] `:"",this.name=s?`[${s}] `:"",this.text=a,this.timestamp=null!==typeof g?this.generateTimestamp(g):""}generateTimestamp(e){switch(e){case LoggerMessage.timestamp.utc:return this.generateUtcTimestamp();case LoggerMessage.timestamp.localedate:return this.generateLocaleDateTimestamp();case LoggerMessage.timestamp.localetime:return this.generateLocaleTimeTimestamp();case LoggerMessage.timestamp.numeric:return this.generateNumericTimestamp();case LoggerMessage.timestamp.locale:return this.generateLocaleTimestamp();default:return""}}generateUtcTimestamp(){return`[${(new Date).toUTCString()}] `}generateLocaleTimestamp(){return`[${(new Date).toLocaleString()}] `}generateLocaleTimeTimestamp(){return`[${(new Date).toLocaleTimeString()}] `}generateLocaleDateTimestamp(){return`[${(new Date).toLocaleDateString()}] `}generateNumericTimestamp(){return`[${Date.now()}] `}toString(){return`${this.timestamp}${this.level}${this.name}${this.context}${this.text}`}}LoggerMessage.level={verbose:0,debug:1,info:2,warning:3,error:4,string:["VRB","DBG","INF","WRN","ERR"]},LoggerMessage.level.stringmap=(new Map).set("verbose",LoggerMessage.level.verbose).set("debug",LoggerMessage.level.debug).set("info",LoggerMessage.level.info).set("warning",LoggerMessage.level.warning).set("error",LoggerMessage.level.error),LoggerMessage.timestamp={utc:0,locale:1,localetime:2,localedate:3,numeric:4},LoggerMessage.timestamp.stringmap=(new Map).set("utc",LoggerMessage.timestamp.utc).set("locale",LoggerMessage.timestamp.locale).set("localetime",LoggerMessage.timestamp.localetime).set("localedate",LoggerMessage.timestamp.localedate).set("numeric",LoggerMessage.timestamp.numeric),"undefined"!=typeof module&&(module.exports=LoggerMessage),"undefined"!=typeof module&&(LoggerMessage=require("./LoggerMessage"));class Logger{constructor(e,{level:t=LoggerMessage.level.info,enabled:s=!0,context:a=null,timestamp:g=LoggerMessage.timestamp.locale,maxlogs:r=0}={}){this.name=e,this.level=t,this.enabled=s,this.context=a,this.timestamp=g,this.maxlogs=r,this.log_count=0}createMessage(e,t){return new LoggerMessage({context:this.context,level:t,name:this.name,text:e,timestamp:this.timestamp})}async log(e,t=this.level){if(this.enabled&&("string"==typeof t&&(t=LoggerMessage.level.stringmap.get(t)),!(t<this.level)))switch("string"==typeof e&&(e=this.createMessage(e,t)),await this.checkLogCount(),this.log_count++,t){case LoggerMessage.level.verbose:await this._verbose(e);break;case LoggerMessage.level.debug:await this._debug(e);break;case LoggerMessage.level.info:await this._info(e);break;case LoggerMessage.level.warning:await this._warning(e);break;case LoggerMessage.level.error:await this._error(e)}}async _verbose(e){e instanceof LoggerMessage&&(e=e.toString()),console.log(e)}async verbose(e){await this.log(e,LoggerMessage.level.verbose)}async _debug(e){e instanceof LoggerMessage&&(e=e.toString()),console.debug(e)}async debug(e){await this.log(e,LoggerMessage.level.debug)}async _info(e){e instanceof LoggerMessage&&(e=e.toString()),console.info(e)}async info(e){await this.log(e,LoggerMessage.level.info)}async _warning(e){e instanceof LoggerMessage&&(e=e.toString()),console.warn(e)}async warning(e){await this.log(e,LoggerMessage.level.warning)}async _error(e){e instanceof LoggerMessage&&(e=e.toString()),console.error(e)}async error(e){await this.log(e,LoggerMessage.level.error)}async checkLogCount(){}}"undefined"!=typeof module&&(module.exports=Logger); | ||
/** | ||
* A log message | ||
*/ | ||
class LoggerMessage { | ||
/** | ||
* Constructor | ||
* @param {Object} options | ||
* @param {String|Null} options.context | ||
* @param {Number|Null} options.level | ||
* @param {String|Null} options.name | ||
* @param {String} options.text | ||
* @param {Number|Boolean} options.timestamp | ||
*/ | ||
constructor({ | ||
context = null, | ||
level = null, | ||
name = null, | ||
text = '', | ||
timestamp = null | ||
}){ | ||
this.context = context ? `[${context}] ` : ''; | ||
this.level = typeof level !== null ? `[${LoggerMessage.level.string[level]}] ` : ''; | ||
this.name = name ? `[${name}] ` : ''; | ||
this.text = text; | ||
this.timestamp = typeof timestamp !== null ? this.generateTimestamp(timestamp) : ''; | ||
} | ||
/** | ||
* Set the timestamp format | ||
* @param {Number} format | ||
*/ | ||
generateTimestamp(format){ | ||
switch(format){ | ||
case LoggerMessage.timestamp.utc: | ||
return this.generateUtcTimestamp(); | ||
case LoggerMessage.timestamp.localedate: | ||
return this.generateLocaleDateTimestamp(); | ||
case LoggerMessage.timestamp.localetime: | ||
return this.generateLocaleTimeTimestamp(); | ||
case LoggerMessage.timestamp.numeric: | ||
return this.generateNumericTimestamp(); | ||
case LoggerMessage.timestamp.locale: | ||
return this.generateLocaleTimestamp(); | ||
default: | ||
return ''; | ||
} | ||
} | ||
/** | ||
* Generate a UTC timestamp. | ||
* eg "Mon, 01 Jul 2019 14:43:35 GMT" | ||
* @return {String} | ||
*/ | ||
generateUtcTimestamp(){ | ||
return `[${(new Date().toUTCString())}] `; | ||
} | ||
/** | ||
* Generate a locale timestamp. | ||
* eg "7/1/2019, 10:43:26 AM" | ||
* @return {String} | ||
*/ | ||
generateLocaleTimestamp(){ | ||
return `[${(new Date().toLocaleString())}] `; | ||
} | ||
/** | ||
* Generate a locale time timestamp. | ||
* eg "10:43:06 AM" | ||
* @return {String} | ||
*/ | ||
generateLocaleTimeTimestamp(){ | ||
return `[${(new Date().toLocaleTimeString())}] `; | ||
} | ||
/** | ||
* Generate a locale date timestamp. | ||
* eg "7/1/2019" | ||
* @return {String} | ||
*/ | ||
generateLocaleDateTimestamp(){ | ||
return `[${(new Date().toLocaleDateString())}] `; | ||
} | ||
/** | ||
* Generate a numerical timestamp. | ||
* eg 1628828513146 | ||
* @return {String} | ||
*/ | ||
generateNumericTimestamp(){ | ||
return `[${Date.now()}] `; | ||
} | ||
/** | ||
* Convert the message to a string | ||
* @returns {String} | ||
*/ | ||
toString(){ | ||
return `${this.timestamp}${this.level}${this.name}${this.context}${this.text}`; | ||
} | ||
} | ||
/** | ||
* LoggerMessage levels | ||
* @type {Object} | ||
*/ | ||
LoggerMessage.level = { | ||
verbose: 0, | ||
debug: 1, | ||
info: 2, | ||
warning: 3, | ||
error: 4, | ||
string: [ | ||
"VRB", | ||
"DBG", | ||
"INF", | ||
"WRN", | ||
"ERR" | ||
] | ||
}; | ||
/** | ||
* Map of strings to LoggerMessage levels | ||
* @type {Map<String, Number>} | ||
*/ | ||
LoggerMessage.level.stringmap = new Map() | ||
.set("verbose", LoggerMessage.level.verbose) | ||
.set("debug", LoggerMessage.level.debug) | ||
.set("info", LoggerMessage.level.info) | ||
.set("warning", LoggerMessage.level.warning) | ||
.set("error", LoggerMessage.level.error); | ||
/** | ||
* Timestamp enum | ||
* @type {Object} | ||
*/ | ||
LoggerMessage.timestamp = { | ||
utc: 0, | ||
locale: 1, | ||
localetime: 2, | ||
localedate: 3, | ||
numeric: 4 | ||
}; | ||
/** | ||
* Map of strings to LoggerMessage timestamps | ||
* @type {Map<String, Number>} | ||
*/ | ||
LoggerMessage.timestamp.stringmap = new Map() | ||
.set("utc", LoggerMessage.timestamp.utc) | ||
.set("locale", LoggerMessage.timestamp.locale) | ||
.set("localetime", LoggerMessage.timestamp.localetime) | ||
.set("localedate", LoggerMessage.timestamp.localedate) | ||
.set("numeric", LoggerMessage.timestamp.numeric); | ||
if(typeof module !== "undefined"){ | ||
module.exports = LoggerMessage; | ||
}if(typeof module !== "undefined"){ | ||
LoggerMessage = require('./LoggerMessage'); | ||
} | ||
/** | ||
* Logs messages and objects to the console. | ||
* | ||
* @example - create a basic logger | ||
* const logger = new Logger("User", { | ||
* level: LoggerMessage.level.debug, | ||
* timestamp: LoggerMessage.timestamp.local | ||
* }); | ||
* logger.debug("Logged in"); // [7/1/2019, 10:43:26 AM] [DBG] [User] Logged in | ||
* | ||
* @example - create a logger as part of an object "Foo" | ||
* this.logger = new Logger("App", { | ||
* level: LoggerMessage.level.info, | ||
* timestamp: false | ||
* context: this | ||
* }); | ||
* logger.info("Initialized"); // [INF] [App] [Foo] Initialized | ||
* | ||
* @example - when logging an object, the object itself is passed to console.log() | ||
* logger.info({name: "Test", count: 100}); // [INF] [App] logging object | ||
* // {name: "Test", count: 100} | ||
*/ | ||
class Logger { | ||
/** | ||
* Constructor | ||
* @param {String} name - Name of the logger | ||
* @param {Object} [params={}] | ||
* @param {Number|String} [params.level=LoggerMessage.level.info] - Starting log level | ||
* @param {Boolean} [params.enabled=true] - Whether the logger is enabled | ||
* @param {String} [params.context=null] - Optional context appended after logger name | ||
* @param {Boolean|Number|String} [params.timestamp=LoggerMessage.timestamp.locale] - Timestamp format | ||
* @param {Number} [params.maxlogs=0] - Maximum number of logs until the first log is deleted | ||
*/ | ||
constructor(name, { | ||
level = LoggerMessage.level.info, | ||
enabled = true, | ||
context = null, | ||
timestamp = LoggerMessage.timestamp.locale, | ||
maxlogs = 0 | ||
}={}) | ||
{ | ||
this.name = name; | ||
this.level = level; | ||
this.enabled = enabled; | ||
this.context = context; | ||
this.timestamp = timestamp; | ||
this.maxlogs = maxlogs; | ||
this.log_count = 0; | ||
} | ||
/** | ||
* Get the timestamp | ||
*/ | ||
get timestamp(){ | ||
return this._timestamp; | ||
} | ||
/** | ||
* Set the timestamp format | ||
* @param {Boolean|Number|String} timestamp | ||
*/ | ||
set timestamp(timestamp){ | ||
if(typeof timestamp === "boolean" && !timestamp){ | ||
this.timestamp = null; | ||
} | ||
else if(typeof timestamp === "string"){ | ||
timestamp = LoggerMessage.timestamp.stringmap.get(timestamp); | ||
} | ||
this._timestamp = timestamp; | ||
} | ||
/** | ||
* Get the level | ||
*/ | ||
get level(){ | ||
return this._level; | ||
} | ||
/** | ||
* Set the level | ||
* @param {Number|String} level | ||
*/ | ||
set level(level){ | ||
if(typeof level === "boolean" && !level){ | ||
this.enabled = false; | ||
} | ||
else if(typeof level === "string"){ | ||
level = LoggerMessage.level.stringmap.get(level); | ||
} | ||
this._level = level; | ||
} | ||
/** | ||
* Create a log message. | ||
* @param {String} text - message to log | ||
* @param {Number} level - log level | ||
* @return {String} | ||
*/ | ||
createMessage(text, level){ | ||
return new LoggerMessage({ | ||
context: this.context, | ||
level: level, | ||
name: this.name, | ||
text: text, | ||
timestamp: this.timestamp | ||
}); | ||
} | ||
/** | ||
* Log a message. Will do nothing if the current | ||
* log level is greater than the specified one. | ||
* @param {String} message - message to log | ||
* @param {Number|String} [level=this.level] - log level; current level by default | ||
* @return {Promise} | ||
*/ | ||
async log(message, level = this._level){ | ||
if(!this.enabled){ | ||
return; | ||
} | ||
// If set as a string, ie "verbose", convert to enum value | ||
if(typeof level === "string"){ | ||
level = LoggerMessage.level.stringmap.get(level); | ||
} | ||
// Check current log level | ||
if(level < this._level){ | ||
return; | ||
} | ||
if(typeof message === "string"){ | ||
message = this.createMessage(message, level); | ||
} | ||
await this.checkLogCount(); | ||
this.log_count++; | ||
switch(level){ | ||
case LoggerMessage.level.verbose: | ||
await this._verbose(message); | ||
break; | ||
case LoggerMessage.level.debug: | ||
await this._debug(message); | ||
break; | ||
case LoggerMessage.level.info: | ||
await this._info(message); | ||
break; | ||
case LoggerMessage.level.warning: | ||
await this._warning(message); | ||
break; | ||
case LoggerMessage.level.error: | ||
await this._error(message); | ||
break; | ||
} | ||
} | ||
/** | ||
* The output function to log a verbose message. | ||
* @param {LoggerMessage|Object} message | ||
* @returns {Promise} | ||
*/ | ||
async _verbose(message){ | ||
if(message instanceof LoggerMessage){ | ||
message = message.toString(); | ||
} | ||
console.log(message); | ||
} | ||
/** | ||
* Log a verbose message. | ||
* Use this level when logging relatively | ||
* unimportant information. Especially useful | ||
* when debugging program flow. | ||
* @param {String} message | ||
* @returns {Promise} | ||
*/ | ||
async verbose(message){ | ||
await this.log(message, LoggerMessage.level.verbose); | ||
} | ||
/** | ||
* The output function to log a debug message. | ||
* @param {LoggerMessage|Object} message | ||
* @returns {Promise} | ||
*/ | ||
async _debug(message){ | ||
if(message instanceof LoggerMessage){ | ||
message = message.toString(); | ||
} | ||
console.debug(message); | ||
} | ||
/** | ||
* Log a debug message | ||
* @param {String} message | ||
* @returns {Promise} | ||
*/ | ||
async debug(message){ | ||
await this.log(message, LoggerMessage.level.debug); | ||
} | ||
/** | ||
* The output function to log an info message. | ||
* @param {LoggerMessage|Object} message | ||
* @returns {Promise} | ||
*/ | ||
async _info(message){ | ||
if(message instanceof LoggerMessage){ | ||
message = message.toString(); | ||
} | ||
console.info(message); | ||
} | ||
/** | ||
* Log an info message | ||
* @param {String} message | ||
* @return {Promise} | ||
*/ | ||
async info(message){ | ||
await this.log(message, LoggerMessage.level.info); | ||
} | ||
/** | ||
* The output function to log a warning message. | ||
* @param {LoggerMessage|Object} message | ||
* @returns {Promise} | ||
*/ | ||
async _warning(message){ | ||
if(message instanceof LoggerMessage){ | ||
message = message.toString(); | ||
} | ||
console.warn(message); | ||
} | ||
/** | ||
* Log a warning message | ||
* @param {String} message | ||
* @returns {Promise} | ||
*/ | ||
async warning(message){ | ||
await this.log(message, LoggerMessage.level.warning); | ||
} | ||
/** | ||
* The output function to log an error message. | ||
* @param {LoggerMessage|Object} message | ||
* @returns {Promise} | ||
*/ | ||
async _error(message){ | ||
if(message instanceof LoggerMessage){ | ||
message = message.toString(); | ||
} | ||
console.error(message); | ||
} | ||
/** | ||
* Log an error message | ||
* @param {String} message | ||
* @returns {Promise} | ||
*/ | ||
async error(message){ | ||
await this.log(message, LoggerMessage.level.error); | ||
} | ||
/** | ||
* Check the number of logs and do something if necessary. | ||
* @returns {Promise} | ||
*/ | ||
async checkLogCount(){ | ||
} | ||
} | ||
if(typeof module !== "undefined"){ | ||
module.exports = Logger; | ||
} |
{ | ||
"name": "@voliware/logger", | ||
"version": "2.0.4", | ||
"version": "2.0.5", | ||
"description": "A tiny Javascript logger with levels and several options. Supports Node, MongoDB, and all modern Browsers", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -40,16 +40,29 @@ # logger | ||
const db = new Logger.Database({ | ||
name: "my-collection", | ||
collection_names: ['logs'] | ||
// Setup MongoDB example | ||
const url = "mongodb://localhost:27017/logger-testing?retryWrites=true&w=majority" | ||
const mongoclient = new MongoClient(url, { | ||
useNewUrlParser: true, | ||
useUnifiedTopology: true | ||
}); | ||
// Optionally disable the databases internal logger | ||
// db.logger.enabled = false; | ||
await this.db.initialize(); | ||
this.collection = await this.db.getCollection('logs') | ||
await mongoclient.connect(); | ||
const mongodb = mongoclient.db("logger-testing"); | ||
await mongodb.createCollection("logs"); | ||
// Create the logger | ||
const mongodblogger = new MongoDbLogger("App", { | ||
collection: mongodb.collection('logs') | ||
}); | ||
``` | ||
}) | ||
### Single Logger | ||
If you want to use a single logger throughout, but want to change the [Name] or [Context] per message, you can pass a `LoggerMessage` object to the associated log function. | ||
```js | ||
logger.debug(new LoggerMessage({ | ||
name: "[Social]", | ||
context: "[Posts]", | ||
text: "Bob posted something" | ||
})) | ||
``` | ||
### API | ||
## API | ||
```js | ||
@@ -56,0 +69,0 @@ logger.verbose("verbose log"); |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
49327
1364
0
95