What JS Logging library / tool do you use?

Daniel Golant on September 14, 2018

I am trying to decide on what logging module to try out for my next project. I'd love the dev community's input on: A) What logging lib you use... [Read Full]
 

There is only one thing I use:

console.log()

And I reset (and remove) my logs after the code has been proven stable. :-) Generally, logging should remain a debugging feature. The users won't need it.

 

I also do this. But Iā€™m curious about other answers in the thread.

 

Since I'm just starting learning node I came to this post with some hesitation since I really didn't know if console.log() was an acceptable answer. Thanks for the clarification. hahaha

 

The problem with using console directly is that there are browsers out there (probably only real old ones though) that simply crash your code right away because console is undefined when the developer tool is not opened. Also some interpreters, such as Nashorn which comes with Java, simply do not have a console defined.

If you want to avert that risk and still only use the console for logging, you should write code similar to this:

var log = (typeof console != 'undefined') && console 
// Testing with typeof is better than window.console 
// since it works everywhere, inclucing Node JS / Nashorn
log && log.info('If the console is not there, this code will not crash')

However, this means testing log before each call to log.info... You could maybe do this to prevent that test:

var log = typeof console != 'undefined' ? console : {info:function(){}}
log.info('This code calls a dummy function if console is not there')

However, you would also have to make dummies for warn(), error() etc... In the end you would be building a shim... Which is exactly how ulog started. I understand your desire to keep logging simple and not use any external libs for it... But really the state of JS today is that 'simple' logging either is broken (crashes on some systems), is not actually 'simple' (see code examples above), or does use a library. I built ulog from the desire to make it as close to using no lib at all, while actually solving those problems. If you never use any logging lib, ulog was built with you in mind! Please try it and let me know.

 

On the front end, I mainly use console.log; however, I turn the logging on and off via an environment variable before I compile. If the logging is turned off, the log function does a no op.

const logFunc = (process.env.NODE_ENV === 'development') ? console.log : () => {};

class Utility {

     static log(...args) {
           // Usually I do some normalization and enhancement here by map over the args
           const enhancedArgs = args.map(arg => JSON.stringify(arg, null, 2))

           // Call the logFunc with console
           logFunc.apply(console, enhancedArgs)
     }

}

On the server side, I use winston and morgan.

 

This is a really good idea that I had never thought of for JS. Is () => {} really a no-op or is there just less overhead? In C, you can use (void) 0 to denote a no-op which would get optimized out in the compiler, but in JS you're interpreted.

 

Please, please try ulog It is just over 1KB and it supports all this stuff out of the box. Plus it has a test suite and everything and does not have the bugs your home-brew implementation will have. I am speaking from experience. I have been developing this simple lib for years now and it is amazing how many things can (and will) go wrong in different environments when it comes to logging.

Basically I am hearing you guys re-inventing the wheel :) ulog has a simple config mechanism via env vars or localStorage that does exactly what you mention here, plus a bit more. Check it out and let me know what you think.

About the no-op thing.... It is probably just minimal overhead, not no overhead. But really if the overhead of an empty function call is an issue in your code, better look very carefully at your code because that should never be an issue.

What could be an issue is if you do this:

log.info(veryExpensiveFunctionCall())

The veryExpensiveFunctionCall() will be performed and the result passed to the no-op method... So still slow.

In ulog we fix that like this:

if (log.level >= log.INFO) {
  log.info(veryExpensiveFunctionCall())
}

The level check makes sure we only call veryExpensiveFunctionCall() if it is really needed.

This code has a weird smell. Can you give me an example of an expensive function call where the only thing you would want to do is log the output in a development environment.

It is an example. The point is that if you do expensive things to produce the arguments of a log call, the fact that the log function is a no-op does not help with performance. In such cases you need the if. The example is there to demonstrate the if.

 

Before I proceed I must warn you I am the author of the logging library I am using, so there is a tiny possibility that I might be biased. Very tiny :)

ulog - The microscopically small universal logger

Basically ulog is debug meets loglevel meets the console. It works in Node JS and all major browsers (even old ones!)

  • Mostly works exactly like the console does
  • Supports levels that map to console methods (info, warn, error...)
  • Supports configuration of log level via query string/localStorage (browser) or environment variables (Node)
  • Supports a debug mode that selectively enables loggers
  • Smart default log levels

Why I built it

It started out because using console directly is basically VERBOTEN. Because some browsers simply don't support it and will crash your code. Also you need to remove these statements afterwards etc. Making logging difficult and error prone. So it started as a tiny shim that just makes sure that your code never crashes or fails whether console is available or not.

I then decided I wanted log level support so I added that. And then I discovered debug, which is GREAT, and I decided to copy those features I loved about that.

Why I think it is one of the best loggers

  • It is SMALL. Some loggers really go overboard but I need this stuff to be tiny. 1K is about all I want to spend on a logging lib
  • It supports levels. Levels make logging useful!
  • It has AWESOME debug features. Just set DEBUG=module1,module2 and these modules will start logging debug info
  • By default, only Error and Warning message will show up in the console in browsers, meaning you can log as much as you want and only those people that are interested in it will actually see it. You can just leave your log statements in your production code. In Node JS we use INFO as the default level because there the 'users' are mostly developers / server admins etc who are more interested in our logging. Using different defaults on different platforms felt weird at first but it actually works out great for my projects.
  • It supports a shorthand form that applies formatting.

Example usage

var ulog = require('ulog')
var log = ulog('my-module')

log.debug('Debug message');
log.info('Info message');
log.warn('Warning message');
log('Formatted message (at debug level)')
log('warn', 'Formatted message (at warning level)')

Yields (on browsers)

Warning message
21:23:24   .03 my-module                Formatted message (at warning level)

If you want to try it

Now is the perfect time as I am trying to perfect v2 currently. So if you want to try this, please install the beta and let me know:

npm install --save ulog@beta

Or you can use v1, but that version is more limited in features:

npm install --save ulog
 

Other than console.log(), there have been morgan, winston, pino and at least hundreds of others.

But, I am very surprised to see no one mentioned debug, it has 22,914,644 weekly downloads as of right this comment.

  • I can filter out and specify different keywords I put beforehand, can use wildcards for multiple keywords/namespace
  • Can have namespace colors
  • Even works on web browser with colorized output
  • can show ms diff between last msg
  • ...lots of other cool features like streams and the list goes on
  • and most importantly it is actively developed

Though it is more of a debugging tool than a logging tool, we do have to log a lot while trying to debug, or in most case debugging is the only goal for logging.

There are obvious gotchas, but who cares as long as I can get to see what I wanted to see.

 

Indeed, debug RULES! So much so I rebuilt my logging lib from scratch so it could incorporate debug's best features.

The biggest gripe I have with it is that it is not full-featured. It basically is ONLY for debug logging. I like to log some info/warning messages as well some times. With debug you still need either a different lib or the console just for that.

 

debug module borks when minimized

You need to configure the compression to let some optimizations through

I also couldnt get it to work on an isomorphic app. Minimizing for node.js and tje web require 2 different approaches

 

For those who use simple console.log() and VS Code as editor, try out wrap-console-log extension.

If you'd like to color your log try chalk.

 
 
 

I've written two posts on logging in JavaScript that might be helpful:
Should you use a logging framework or console.log() in Node?

^ In this one I make the argument that often console.log() and console.error() are enough to get the job done, unless you have a use case for custom log levels, for writing to different outputs/locations (I recommended against doing this), or need the ability to toggle logs on and off.

If I do have that use case I use Winston as it's pretty well supported.

Why should your Node.js application not handle log routing?

^ this one hopefully helps answer your question about storing logs and logging infrastructure

I always write to stdout/stderr (the console module writes here) as it's really easy for Docker or other containers to pick up the logs from there and route them wherever you need to (Splunk, a database, etc.).

In a container/distributed/cloud environment it becomes much easier to manage the logs and adheres to the 12 Factor best practices for logging.

In this way, the log routing is decoupled from the concerns of the application. All the application then cares about is writing to console, and infrastructure-wise, the container picks up the logs and takes care of them from there.

 

console.log and node app.js > app.log work fine most of the time.

Sometimes, if I need to filter logs and stuff, I write them as json objects instead of plain files and create a very simple wrapper over console.log, but I've never had the need to do anything very elaborated.

 

console.log(), but are you using node? Noticed it in your tag. If that's the case you can require fs and write logs out to your filesystem. Also check out console.table for iterable objects, and also console.assert

 
 

Yes. Sorry, on my phone when I punched that out. Also look into console.error()

 

I'am using log4js in my project. But most of time I still using console.log() for debugging

 

I like using this, too. Log levels are super helpful

 
 

It is great but not very well supported I think? Does this work in Edge? Firefox?

 

I have, a long time ago, registered the NPM package name anylogger, because basically logging in JS is a royal mess. If you build an app out of a few dozen packages, chances are you end up including 5 different logging libraries because every module chooses it's own logger.

Wouldn't it be much better if libraries would use a facade to log and leave the choice of the actual logger (and it's config) to the final app? A bit like what SLF4J is doing in Java land, but much simpler of course ;)

This is what anylogger is supposed to be... a Facade that libs can use and that can be replaced by a real logger like Winston, Bunyan, Loglevel, Debug, or, of course, Ulog.

If you are interested in this, please check it out. It's mostly in pipe-dream stage at the moment though. But I would love to hear feedback on this.

 

my use cases :

1- in case of using Docker
A) Winston to log and store in txt file
B) structure based on the Service name, and Environment (stg or production)
C) Store in txt file, use filebeat to harvest and push to Logstash to index and store in Elastic search. then visualise it Kibana (ELK stack)

2- in case of using AWS Lambda
A) simple "console.log()"
B) not really
C) just use AWS CloudWatch

 
 

Seems like a lot of people use winston. I primarily use serilog (.NET), the reason I love it and bring it up is because it's a fully-structured logger. I can't speak to winston's capabilities, but I know bunyan offers similar features in node which I highly recommend finding.

 

Winston has been my daily driver for a while.
Having different transport methods, easily changing the logging level and the handling uncaught exceptions makes debugging a lot better!

This is a game changer, specially on old code!

 

A) I use a combination of morgan for request logging, and Winston for error logs.

B) I structure my logs into information logs, warning logs, request logs, and error logs.

  • The information logs are used for things like user sign-in, database modifications, and algorithm analysis.
  • Warning logs are things like the user was denied access, A resource is using up too much memory or taking too long, or a result that doesn't break the system, but could be a problem for the user.
  • Error logs are reserved for runtime errors or anything where a system actually failed to perform its job.
  • The request logs are handled by Morgan and they mainly log the request made to the server, the parsed query (using GraphQL), and the response to the user.

C) I store my logs in a logs folder on the production server. They are organized into 3 files based on the level of severity, and each log entry is prepended with a time stamp, and the userId if applicable.

 

For all you guys out there using the console directly, because you don't want to commit to some logging library, I came up with anylogger. It is a ~360 bytes minified and gzipped logging shim that wraps the console. But it is also a facade object that supports an adapter pattern to plug in support for the logging framework of choice.

For example, if you were building my-library, you could install anylogger like this:

npm install --save anylogger

Then in your code, you would create and use a logger like this:

my-library.js

var anylogger = require('anylogger')
var log = anylogger('my-library')
log('Logging is simple!')

This adds a tiny, ~360 bytes overhead to your library, but you now have configurable logging support. Suppose you discover you really like debug and want to use it in your new project that is using my-library. Here is how you would install my-library into your application project and make it use debug:

npm install --save my-library anylogger debug anylogger-debug

This installs my-library, anylogger, debug and the anylogger-debug adapter.

Then, in your main.js, just require the adapter and it will work:

main.js

require('anylogger-debug')
var debug = require('debug')
debug.enable('my-library')
// you should start to see logging from 'my-library'
// in the format expected from debug

I am working towards an 1.0 release and would appreciate feedback.

 

Haven't heard of Winston before this post. Looks really cool for creating log files based on the console statements used in the code!

 

I used winston, bunyan and pino (also console.log šŸ˜…) on nodejs apps to log all application activity and storing using some "log rotate" plugin.

 
 

We are using loglevel github.com/pimterry/loglevel to log errors and to debug code. Currently not storing the logs. All the "debug" logs are disabled in production builds.

 

I have used and enjoyed bunyan. Used in combination with bunyan-format it improved the project.

You can see it used in my project here:
github.com/joelnet/bitcoin-all-tim...

 
 

like you, I've been using Winston (am still using it)

 

Winston, logging to console in development and console plus elastic stack in production.

I like the feature of sending JSON to elastic with the resulting possibility of organizing (filtering, sorting, searching, columns, ...) based on those JSON keys.

 
code of conduct - report abuse