@voliware/logger
Advanced tools
Comparing version 2.0.5 to 2.0.6
@@ -6,2 +6,2 @@ const NodeBuild = require('@voliware/node-build'); | ||
const output = './dist/logger.min.js'; | ||
new NodeBuild.Build({name, version, input, output}).run(); | ||
new NodeBuild.FileBuilder({name, version, input, output, minify: true}).run(); |
@@ -1,441 +0,1 @@ | ||
/** | ||
* 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; | ||
} | ||
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}get timestamp(){return this._timestamp}set timestamp(e){"boolean"!=typeof e||e?"string"==typeof e&&(e=LoggerMessage.timestamp.stringmap.get(e)):this.timestamp=null,this._timestamp=e}get level(){return this._level}set level(e){"boolean"!=typeof e||e?"string"==typeof e&&(e=LoggerMessage.level.stringmap.get(e)):this.enabled=!1,this._level=e}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); |
{ | ||
"name": "@voliware/logger", | ||
"version": "2.0.5", | ||
"version": "2.0.6", | ||
"description": "A tiny Javascript logger with levels and several options. Supports Node, MongoDB, and all modern Browsers", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
# logger | ||
Probably the simplest logger out there. | ||
Probably the simplest logger out there. Now with a little more kick. | ||
Version 2 introduces breaking changes, as well as new `FileLogger` and `MongoDbLogger` classes. | ||
## How to Use it | ||
### Use it in the Browser or Node.js | ||
```js | ||
const {Logger} = require('@voliware/logger'); // Node only | ||
const logger = new Logger("App", { | ||
level: "debug", // LoggerMessage.level | ||
timestamp: "utc" // LoggerMessage.timestamp | ||
level: "debug", // or LoggerMessage.level.debug | ||
timestamp: "utc" // or LoggerMessage.timestamp.utc | ||
}); | ||
@@ -26,2 +26,3 @@ | ||
filepath: "/path/to/file.log", | ||
timestamp: false, | ||
maxlogs: 10000, | ||
@@ -39,3 +40,3 @@ maxsize: 1024 * 1000, | ||
```js | ||
const Logger = require('@voliware/logger'); | ||
const {MongoDbLogger} = require('@voliware/logger'); | ||
@@ -51,2 +52,3 @@ // Setup MongoDB example | ||
await mongodb.createCollection("logs"); | ||
// Create the logger | ||
@@ -69,3 +71,3 @@ const mongodblogger = new MongoDbLogger("App", { | ||
## API | ||
## Logger API | ||
```js | ||
@@ -79,7 +81,33 @@ logger.verbose("verbose log"); | ||
logger.log("hello again", Logger.level.debug); | ||
logger.name = "App"; | ||
logger.context = "Users"; | ||
logger.timestamp = "numeric"; | ||
logger.level = "info"; | ||
logger.enabled = false | ||
logger.enabled = false; | ||
logger.maxlogs = 1000; | ||
logger.maxlogs = 0; // no limit | ||
logger.maxsize = 1024 * 1024; | ||
logger.maxsize = 0; // no limit | ||
``` | ||
## FileLogger API | ||
```js | ||
logger.console = false; // don't also print to console | ||
logger.filepath = 'path/to/file.ext'; | ||
logger.maxsize = 1024 * 1024; | ||
logger.maxsize = 0; // no limit | ||
//logger.multiplefiles = true; // future | ||
logger.clear(); | ||
logger.delete(); | ||
logger.rename('new/file/name.ext'); | ||
``` | ||
## MongoDbLogger API | ||
```js | ||
logger.console = false; // don't also print to console | ||
logger.collection = collection; // native MongoDB collection | ||
logger.clear(); | ||
``` | ||
## Node | ||
@@ -86,0 +114,0 @@ Install with node package manager |
@@ -69,2 +69,10 @@ const EOL = require('os').EOL; | ||
/** | ||
* Set the console logging state | ||
* @param {Boolean} state | ||
*/ | ||
set console(state){ | ||
this.console_logger.enabled = state; | ||
} | ||
/** | ||
* Open the write stream | ||
@@ -71,0 +79,0 @@ */ |
@@ -40,2 +40,10 @@ const Logger = require('./logger'); | ||
/** | ||
* Set the console logging state | ||
* @param {Boolean} state | ||
*/ | ||
set console(state){ | ||
this.console_logger.enabled = state; | ||
} | ||
/** | ||
* Clear the collection | ||
@@ -42,0 +50,0 @@ */ |
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
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
123
42534
979
1