npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

lokua.net.node-logger

v0.11.2

Published

Configurable logging for node.js with easy to use API; connect/express/koa request logging middleware are included

Downloads

2

Readme

lokua.net.node-logger

Configurable logging for node.js with easy to use API; connect/express/koa request logging middleware included

You should use Logger if

  • You want a logger that works exactly like console.log|trace|info|warn|error
  • You want to be able to easily customize all aspects of your logs without having to learn a complete DSL
  • You don't mind taking the 12factor approach and piping your logs to stdout instead of having to mess around with environment/conditional logic governing when to use a file vs console etc

For a browser version with almost identical API, see lokua.net.logger

Install

npm install lokua.net.node-logger

Usage

const Logger = require('../lib')

const logger = new Logger('foo')
logger.info('Hello, world!')

// or with some customization
const logger2 = new Logger('bar', {
  format: ['date', 'name', 'level'],
  dateType: 'locale',
  dateOutput: 'time'
})

const obj = { a: 1 }

// supports both node and browser format specifiers
logger2.debug('obj: %o', obj)

example.png

API

Logger(name, [level|options])

Overview

The Logger constructor takes a required name and optional level, or options hash. Currently Logger supports the following wrapped console methods (check out mdn:console for basic console usage):

  • log
  • trace
  • debug (via log)
  • info
  • warn
  • error

A Logger instance will only log calls that are greater or equal to its current level. For example if an instance is set to level 5, only errors will be logged. This level is per logger, so Logger A's level will not effect Logger B. There is a global off switch available through the static Logger.off, which will silence all loggers regardless of their level.

The order of the levels are as follows:

  • 0 (aka Logger.LOG) : log
  • 1 (aka Logger.TRACE) : trace
  • 2 (aka Logger.DEBUG) : debug
  • 3 (aka Logger.INFO) : info
  • 4 (aka Logger.WARN) : warn
  • 5 (aka Logger.ERROR) : error

Customization

Every log message is prefixed according to Logger#options.format array, which sets both the ordering of formats and whether to include them. The default format is ['name', 'level', 'date', 'source']. Each of these format's colors can be set to any valid chalk color through Logger#options.<name|level|date|source>Color.

Example

const logger = new Logger('MAIN', {

  // only log warnings and errors
  level: Logger.WARN,

  // custom format order excluding `name` and `source`
  format: ['date', 'level']

  dateColor: 'blue',
})

The date format can further be customized through #options.dateType and #options.dateOutput.

Here are all possible configurations


# dateType=iso
# dateOutput=datetime
[2015-12-30T06:43:14.759Z]
# dateOutput=date
[2015-12-30]
# dateOutput=time
[06:43:14.768Z]

# dateType=utc
# dateOutput=datetime
[Wed, 30 Dec 2015 06:43:14 GMT]
# dateOutput=date
[Wed, 30 Dec 2015 ]
# dateOutput=time
[06:43:14 GMT]

# dateType=locale,
# dateOutput=datetime
[12/30/2015, 12:43:14 AM]
# dateOutput=date
[12/30/2015]
# dateOutput=time
[12:43:14 AM]

If you require something more unique, you can bypass dateType|Output entirely by supplying a custom formatter through #options.dateFormatter

logger.options.dateFormatter = date => date.toISOString().replace(/\W+/g, '')
// => '20151230T065057049Z'

See: Logger._defaultOptions

Params:
  • name {String}the name of this Logger instance

  • [level|options] {Object|Number}Either a hash with configuration options, or a number setting this instance's logging level.

Logger#level

Convenience getter/setter for Logger#options.level

Logger#setOptions([options])

Set multiple options at once. If called with no arguments, null, or an empty object, #setOptions will restore the default options

Params:
  • [options] {Object}
Return:
  • {this}

Logger#log()

console#log wrapper

Return:
  • {Logger} this

Logger#trace()

console#trace wrapper

Return:
  • {Logger} this

Logger#debug()

console#log wrapper

Return:
  • {Logger} this

Logger#info()

console#info wrapper

Return:
  • {Logger} this

Logger#warn()

console#warn wrapper

Return:
  • {Logger} this

Logger#error()

console#error wrapper

Return:
  • {Logger} this

Logger.getLogger(name)

Get a Logger instance by name

Params:
  • name {String}The name as passed to the Logger constructor
Return:
  • {Logger} the logger instance or undefined if no match

Logger.setDefaults(defaults)

Override the factory defaults for all Loggers. New defaults object will be merged with existing. Note that these defaults can not be restored

Params:
  • defaults {Object}

Logger.connectLogger(name, [options])

Create request logging middleware for connect/express. This method's parameters are identical to the Logger constructor, except that the default format is ['date', 'name']

Example

connect.test.js:

const connect = require('connect')
const http = require('http')
const Logger = require('lokua.net.node-logger')

const app = connect()

app.use('/', Logger.connectLogger('request'))

app.use('/foo', (req, res, next) => {
  res.end('200')
  next()
})

http.createServer(app).listen(3000)

Then from bash:

curl http://localhost:3000/foo
# => 200
curl http://localhost:3000/bar
# => Cannot GET /bar

Log output:

connect.png

Params:
  • name {String}the identifier for the request logger

  • [options] {Object}Options hash.

Return:
  • {Function} logging middleware

Logger.koaLogger(name, [options])

Create request logging middleware for koa.js. This method's parameters are identical to the Logger constructor, except that the default format is ['date', 'name'], and an additional regExp option is supported.

Example

koa.test.js:

const koa = require('koa')
const Logger = require('lokua.net.node-logger')
const app = module.exports = koa()

app.use(Logger.koaLogger('request'))

app.use(function*() {
  if (this.url === '/foo') this.status = 200
})

app.listen('3000')

Then from bash:

curl http://localhost:3000/foo
# => 200
curl http://localhost:3000/bar
# => Cannot GET /bar

Log output:

koa.png

Params:
  • name {String}the identifier for the request logger

  • [options] {Object}Options hash. Same as passed to the Logger constructor. the koaLogger takes an addition regExp argument, which will be matches against incoming request urls, so you can pick and choose what parts of your api will be logged

Return:
  • {Function} logging middleware

Logger.off

Disable logging for all Loggers

Logger.pad

Align logger names and levels. Valid values include 'left', 'right', or false

Logger._defaults

Default options for all Logger instances

Properties:
  • level {Number}The logger's level. After instantiation, the level can be set directly via Logger#level

  • format {Array}et the order of the log prefix. alid values include name, level, date, source.

  • dateType {String}Set the output type of the date format. Valid values include iso, utc, and locale, which refer to their respective Date#to***String methods

  • dateOutput {String}Set whether to include date, time, or datetime in the date format.

  • dateFormatter {Function}Provide a custom date formatting function. The function will be called with a Date object. Note that providing a dateFormatter will cause the dateType and dateOutput options to be ignored, but it has no impact on the dateStyle option

  • useAbsoluteSource {Boolean}If true, output the full absolute path to the sourcecode; otherwise, just the filename, line, and column

  • levelColor {String}chalk color for the log's level output

  • sourceColor {String}chalk color for the log's source output

  • nameColor {String}chalk color for the log's name output

  • dateColor {String}chalk color the log's date output

  • newLine {Boolean}If true, separates a log's prefix and message with a newline

  • stackDepth {Number}In order to output source code line numbers, Logger internally generates a stack trace to find where the logger method was called. Since the Console api is unstable and varies between Chrome versions, the exact location is not always the same; hence, stackdepth. Use this only if Logger is reporting incorrect line outputs.

  • default {Array}colors to use for level formats when Logger#options.levelColor is set to 'auto'. The order of the colors in the array are the same as the levels themselves (log===0, error===5)

License

The MIT License (MIT) Copyright (c) 2015, 2016 Joshua Jay Kleckner

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.