@wizim-dev/logger
v0.0.1
Published
Logger helper to log anything in node JS
Downloads
435
Maintainers
Readme
Logger
Logger helper for Nodejs application
Getting Started
To use this module in your project, install the npm package
npm install '@snark/logger'Usage
import logger from './index';
function printConsole(info) {
let str = `${info.timestamp} - ${info.level} - ${info.message}`;
if (info.prefix) {
str = `${info.prefix} - ${str}`;
}
if (info.suffix) {
str = `${str} - ${info.suffix}`;
}
if (info.newLine === true) {
str = `\n${str}`;
}
return str;
}
logger.formatConsole = logger.winston.format.combine(
logger.winston.format.timestamp(),
logger.winston.format.errors({stack: true}),
logger.winston.format.colorize(),
logger.winston.format.printf(printConsole)
);
logger.meta = {prefix: 'Test prefix'};
logger.addConsoleTransport();
logger.log('debug', 'test logging', {suffix: '\tFin du log', newLine: true});Default Transports
You can add 2 default transports once it has been imported
addConsoleTransport(options)
The Console transport takes a few simple options:
- level: Level of messages that this transport should log (default:
debug). - silent: Boolean flag indicating whether to suppress output (default: false).
- eol: string indicating the end-of-line characters to use (default:
os.EOL) - stderrLevels: Array of strings containing the levels to log to stderr instead of stdout, for example
['error', 'debug', 'info']. (default:[]) - consoleWarnLevels: Array of strings containing the levels to log using console.warn or to stderr (in Node.js) instead of stdout, for example
['warn', 'debug']. (default:[]) - format: Logform formatter (default: See formatConsole)
- handleExceptions: Handling Uncaught Exceptions with winston (default:
true)
addMongoTransport(options)
The MongoDB transport takes the following options. 'db' is required:
- level: Level of messages that this transport should log (default:
debug). - silent: Boolean flag indicating whether to suppress output (default:
false). - format: Logform formatter (default: See formatMongo
- db: MongoDB connection uri. required
- options: MongoDB connection parameters (default:
{poolSize: 2, autoReconnect: true}). - collection: The name of the collection you want to store log messages in (default:
'log'). - storeHost: Boolean indicating if you want to store machine hostname in logs entry, if set to true it populates MongoDB entry with 'hostname' field, which stores os.hostname() value.
- username: The username to use when logging into MongoDB.
- password: The password to use when logging into MongoDB. If you don't supply a username and password it will not use MongoDB authentication.
- label: Label stored with entry object if defined.
- capped: In case this property is true, winston-mongodb will try to create new log collection as capped (default:
false). - cappedSize: Size of logs capped collection in bytes (default:
10000000). - cappedMax: Size of logs capped collection in number of documents.
- tryReconnect: Will try to reconnect to the database in case of fail during initialization. Works only if db is a string. (default:
false). - expireAfterSeconds: Seconds before the entry is removed. Works only if capped is not set.
addCustomTransport(transport)
Adding a custom transport is easy. All you need to do is accept any options you need, implement a log() method, and consume it with winston. In addition, there are additional transports written by members of the community.
Levels
Logging levels in winston conform to the severity ordering from most important to least important error, warn, info and debug
import logger from '@snark/logger'
logger.addConsoleTransport(
{level: 'error'}
);Formatter
You can override default transport with helpers formatConsole and formatMongo() before adding default transports
formatConsole
Default formatter used by addConsoleTransport()
function ignoreConsole(info) {
if (info.ignoreConsole) {
return false;
}
return info;
}
function customFormatUuid(info) {
let uuid = gettingNamespace() || null; // internal method to retrieve namespace
if (uuid) {
info.uuid = uuid;
}
return info;
}
function objectToString(info, opts) {
if (info.message && typeof info.message === 'object') {
info.message = inspect(info.message, false, null, opts.colorize);
}
return info;
}
function printConsole(info) {
let str = `${info.timestamp} - ${info.level} - ${info.message}`;
if (info.uuid) {
str = `${info.uuid} - ${str}`;
}
if (info.prefix) {
str = `${info.prefix} - ${str}`;
}
if (info.stack) {
str = `${str}\n${info.stack}`;
}
if (info.suffix) {
str = `${str} - ${info.suffix}`;
}
if (info.newLine) {
str = `\n${str}`;
}
return str;
}
formatConsole = format.combine(
format(ignoreConsole)(),
format.timestamp(),
format(customFormatUuid)(),
format(objectToString)(),
format.colorize(),
format.printf(printConsole)
);formatMongo
Default formatter used by addMongoTransport()
function ignoreMongo(info) {
if (info.ignoreMongo) {
return false;
}
return info;
}
function customFormatUuid(info) {
let uuid = gettingNamespace() || null; // internal method to retrieve namespace
if (uuid) {
info.uuid = uuid;
}
return info;
}
formatMongo = format.combine(
format(ignoreMongo)(),
format.timestamp(),
format(customFormatUuid)(),
format.uncolorize()
);Meta
You can add global meta to each log request with setter meta and retrieve it with getter meta
By adding {newLine: true} into global meta, each log will generate a new line before printing
import logger from '@snark/logger'
logger.meta = {env: process.env.NODE_ENV};
const meta = logger.meta;Express Router
Use logger router method to log information about express routes
The createRouter(options) method takes the following options.
- level: Level of messages that this transport should log (default:
info). - fields Fields from express
requestto log (default:['hostname', 'method', 'originalUrl', 'path', 'params', 'protocol', 'query', 'route', 'subdomains']).
import logger from '@snark/logger'
import express from 'express';
const app = express();
let api = logger.createRouter();
api.get('/ping', function (req, res) {
res.json({ping: true});
});
app.use('/1.0', api)Namespace
namespaceExpressMiddleware()
Generate an uuid to each express request and store it into winston info stream
import express from 'express'
import logger from '@snark/logger'
const app = express();
app.use(logger.namespaceExpressMiddleware());runInNamspace(method, uuid = uuid())
Helper method to create a namespace and generate an uuid for a specific method
import logger from '@snark/logger'
logger.addConsoleTransport();
logger.runInNamespace(function () {
logger.info("Log with an uuid inside a method");
})
logger.runInNamespace(function () {
logger.info("Log with an uuid equal to 'GLOBAL'");
}, 'GLOBAL')setUuid(value)
Helper to directly set a namespace uuid.
import express from 'express'
import logger from '@snark/logger'
const app = express();
app.use((req, res, next) => {
logger.setUuid('custom-uuid-set-for-each-request');
next();
});
logger.addConsoleTransport();Helper methods
createLogger(options)
Helper method to create the winston instance Automatically called when using any log or transport method A logger accepts the following parameters
| Name | Default | Description |
| ------------- | --------------------------- | --------------- |
| level | 'info' | Log only if info.level less than or equal to this level |
| levels | winston.config.npm.levels | Levels (and colors) representing log priorities |
| format | winston.format.json | Formatting for info messages |
| transports | [] (No transports) | Set of logging targets for info messages |
| exitOnError | true | If false, handled exceptions will not cause process.exit |
| silent | false | If true, all logs are suppressed |
import logger from '@snark/logger'
const options = {}; // winston options
logger.createLogger(options);winstonInstance
Helper method to get the real winston logger instance (null if not yet created)
import logger from '@snark/logger'
logger.createLogger();
const winstonInstance = logger.winstonInstance;
winstonInstance.debug('test');winston
Helper method to get the winston object imported from winston module
import logger from '@snark/logger'
const winston = logger.winston;