GithubHelp home page GithubHelp logo

mixu / minilog Goto Github PK

View Code? Open in Web Editor NEW
377.0 11.0 53.0 365 KB

Lightweight client & server-side logging with Stream-API backends

Home Page: http://mixu.net/minilog/

License: Other

Makefile 2.83% JavaScript 93.02% HTML 4.14%

minilog's Introduction

minilog

Lightweight client & server-side logging with Stream-API backends

Features

  • Works in the browser and on the server
  • Themes for Node console output, and for the Chrome console (with fallbacks)
  • Interface compatibility with Node and browser consoles, that is, you can replace console.* calls with Minilog since it supports (.log, .debug, .info, .warn and .error)
  • Each log message can be associated with a namespace.
  • Log output can be filtered by namespace and log level.
  • Pipe to one or more backend streams at the same time
  • Backends:
    • Node: Console, File (and all other WritableStreams), Redis
    • Browser: Console, LocalStorage, jQuery.ajax
  • In Chrome, we support theming the dev console output.

See the docs at http://mixu.net/minilog/.

Upgrading from 2.x to 3.x

v3.0 changes the ajax logger's POST payload from newline-separated JSON lines to a hash { logs: [ ... ] }. Previously, this format was only used if logger.extras was set. This makes the POST payload parseable as JSON directly, but may require you to update your logging endpoint if you were using v2.x before.

Pipes everywhere

minilog is more convention than code. The logger is a EventEmitter, and backends are Writable streams. Filters and formatters are duplex (readable + writable) streams.

minilog works in Node, and in the browser:

// logs are scoped to a namespace for easy filtering (here, the namespace is "app")
var log = require('minilog')('app');
require('minilog').enable();

in the browser (via a single exported global window.Minilog):

<script src="dist/minilog.js"></script>
<script>
var log = Minilog('app');
Minilog.enable();
</script>

Usage:

// assuming you've done the two things above
log
  .debug('debug message')
  .info('info message')
  .log('info message')
  .warn('warning')
  .error('this is an error message');

Output:

screenshot3

To log to the console:

require('minilog').enable();
// or .pipe(process.stdout), if you don't want the default formatting and filtering

To log into a file:

require('minilog').pipe(fs.createWriteStream('./temp.log'));

You can also log to Redis and over HTTP to a RESTful API, see the backends at the end of this page.

You can pipe to more than one endpoint if you want.

Installation

For Node:

$ npm install minilog

You can find a ready-made file for the web in ./dist/minilog.js.

Upgrading from minilog v1

Everything is now a pipe, which means that the .format() and .filter() functions are deprecated. Check out the new filter mechanism docs. To apply a formatter, you should pipe the input into the formatter, and then pipe it to the desired backend:

var Minilog = require('minilog');

Minilog.pipe(Minilog.backends.console.formatWithStack)
       .pipe(Minilog.backends.console);

Enabling logging

Minilog output is suppressed by default. To enable logging, append minilog=1 to the page URL:

http://www.example.com/index.html?minilog=1

or call Minilog.enable() from the dev console or in code. On the browser, this also sets a value in LocalStorage so that logging is enabled on subsequent reloads. Call Minilog.disable() (new in v2) to stop logging.

Filtering

Minilog supports filtering via the log scope name and the log level, as well as a number of nifty features. See the filtering docs for more.

Formatting & themes

Minilog supports themes and custom formatters, and comes several with built-in themes:

screenshot

screenshot2

To enable a specific theme, pipe to the formatter and then to the console:

var Minilog = require('minilog');

Minilog
    // formatter
    .pipe(Minilog.backends.console.formatClean)
    // backend
    .pipe(Minilog.backends.console);

Have a look at ./test/examples/themes_example.js.

To write your own formatter, have a look at the source code for the formatters - they inherit from Minilog.Transform.

Using Minilog as a console replacement

If you use an injected console object to log browser or Node.js activity, you can use Minilog instead: they have similar interfaces. Minilog provides a log() method, which proxies to debug().

So for instance, the following snippet:

function doThings(console) {
    if (problem) {
        console.error('problem');
        return;
    }
    console.log('no problem');
}

Works seamlessly with Minilog instead of console:

var Minilog = require('minilog');
doThings(Minilog);

Backends

Backends are Writable streams which handle stringification.

Node: Console, Redis

The console backend is literally this (plus code for pretty printing log lines in various ways):

{
  write: function(str) { process.stdout.write(str); }
}

The Redis backend is almost equally simple - it accepts client (an instance of node-redis) and key and uses rpush() to add to the list at the specified key.

Browser: Array, Console, jQuery, localStorage

The Array backend stores the log lines into an array. This is useful if you want to keep a list of all the log lines, e.g. for error reporting. Call .get() to get the array, and .clear() to empty it.

The Console backend makes sure that console.log is available. On IE8 and IE9, it tries to make the console a bit less aweful by using JSON.stringify to convert objects into strings (rather than "[Object object]").

The jQuery backend is useful for logging client-side log lines on the server side:

  • it sends new log messages as a POST request to a given URL every 30 seconds
  • if localStorage is available, logs are written to localStorage as well. This is helpful because it reduces the risk that you lose log lines just because the client navigates to a different page.
  • Unsent logs from localStorage are sent the next time the backend is activated (on your domain, localStorage is isolated).
  • No errors, even if localStorage is not available or jQuery is not defined (though no POST requests if no jQuery).

The localStorage backend just writes logs to the given key in localstorage.

Have a look at the example server setup in ./test/examples/jquery_server.js.

minilog's People

Contributors

aymericbouzy avatar fzaninotto avatar itaykomemy avatar marklemerise avatar mikito-stripe avatar mixu avatar nherment avatar riddla avatar roark avatar ryanseddon avatar taji avatar wclr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

minilog's Issues

How to target angular 2 components instead of node modules ?

To white list, we do:

       Minilog.suggest.defaultResult = false; // Enable Whitelist Mode
        Minilog
            .suggest
            .clear()
            .allow(component,level);
        Minilog.enable();

Would if be possible to target angular2 components to steer the logging on the granular level like with node js modules?

Get rid of legacy octal escape

Hi! ๐Ÿ‘‹

Firstly, thanks for your work on this project! ๐Ÿ™‚

Today I used patch-package to patch [email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/minilog/lib/node/formatters/npm.js b/node_modules/minilog/lib/node/formatters/npm.js
index c0b7a23..2de3061 100644
--- a/node_modules/minilog/lib/node/formatters/npm.js
+++ b/node_modules/minilog/lib/node/formatters/npm.js
@@ -6,12 +6,12 @@ Transform.mixin(FormatNpm);
 
 FormatNpm.prototype.write = function(name, level, args) {
   var out = {
-        debug: '\033[34;40m' + 'debug' + '\033[39m ',
-        info: '\033[32m' + 'info'  + '\033[39m  ',
-        warn: '\033[30;41m' + 'WARN' + '\033[0m  ',
-        error: '\033[31;40m' + 'ERR!' + '\033[0m  '
+        debug: '\x1b[34;40m' + 'debug' + '\x1b[39m ',
+        info: '\x1b[32m' + 'info'  + '\x1b[39m  ',
+        warn: '\x1b[30;41m' + 'WARN' + '\x1b[0m  ',
+        error: '\x1b[31;40m' + 'ERR!' + '\x1b[0m  '
       };
-  this.emit('item', (name ? '\033[37;40m'+ name +'\033[0m ' : '')
+  this.emit('item', (name ? '\x1b[37;40m'+ name +'\x1b[0m ' : '')
           + (level && out[level]? out[level] : '')
           + args.join(' '));
 };
diff --git a/node_modules/minilog/lib/node/formatters/util.js b/node_modules/minilog/lib/node/formatters/util.js
index 4288e6c..ad1e90b 100644
--- a/node_modules/minilog/lib/node/formatters/util.js
+++ b/node_modules/minilog/lib/node/formatters/util.js
@@ -1,20 +1,20 @@
 var styles = {
     //styles
-    'bold'      : ['\033[1m',  '\033[22m'],
-    'italic'    : ['\033[3m',  '\033[23m'],
-    'underline' : ['\033[4m',  '\033[24m'],
-    'inverse'   : ['\033[7m',  '\033[27m'],
+    'bold'      : ['\x1b[1m',  '\x1b[22m'],
+    'italic'    : ['\x1b[3m',  '\x1b[23m'],
+    'underline' : ['\x1b[4m',  '\x1b[24m'],
+    'inverse'   : ['\x1b[7m',  '\x1b[27m'],
     //grayscale
-    'white'     : ['\033[37m', '\033[39m'],
-    'grey'      : ['\033[90m', '\033[39m'],
-    'black'     : ['\033[30m', '\033[39m'],
+    'white'     : ['\x1b[37m', '\x1b[39m'],
+    'grey'      : ['\x1b[90m', '\x1b[39m'],
+    'black'     : ['\x1b[30m', '\x1b[39m'],
     //colors
-    'blue'      : ['\033[34m', '\033[39m'],
-    'cyan'      : ['\033[36m', '\033[39m'],
-    'green'     : ['\033[32m', '\033[39m'],
-    'magenta'   : ['\033[35m', '\033[39m'],
-    'red'       : ['\033[31m', '\033[39m'],
-    'yellow'    : ['\033[33m', '\033[39m']
+    'blue'      : ['\x1b[34m', '\x1b[39m'],
+    'cyan'      : ['\x1b[36m', '\x1b[39m'],
+    'green'     : ['\x1b[32m', '\x1b[39m'],
+    'magenta'   : ['\x1b[35m', '\x1b[39m'],
+    'red'       : ['\x1b[31m', '\x1b[39m'],
+    'yellow'    : ['\x1b[33m', '\x1b[39m']
   };
 
 exports.levelMap = { debug: 1, info: 2, warn: 3, error: 4 };

This issue body was partially generated by patch-package.

AjaxLogger sets contentType: 'application/json' incorrectly

Currently each line is individually a valid JSON string, but the whole body itself is not. Currently it looks like:

["myApp","info",some text"]
["myApp","info","some more text"]
["myApp","info","even more text"]

when really it should look like this:

{"logs: [
  ["myApp","info",some text"]
  ["myApp","info","some more text"]
  ["myApp","info","even more text"]
]}

If we're not prepared to do this, we should absolutely not set the contentType to be 'application/json'. This screws up the node json body-parser, which will try to JSON.parse the whole body if the contentType matches.

Getting localStorage to act as a cache for ajax requests

I have tried to get it to work but with no avail. From looking at the code it seems like it is not supported.

From the website:
"Unsent logs from localStorage are sent the next time the backend is activated (on your domain, localStorage is isolated)."
So it seems like it should be implemented already.
Could you explain how to set that up?

Many Thanks,
Itay.

Better configurability for the browser env

I want to easily disable/enable console output, without using the localStorage configuration mechanism which requires that you remember a specific string.

I also want to set the logging level (e.g. only warn etc.).

I also want to enable/disable by particular logging scopes.

I also want an alternative to localstorage, such as being able to pass a string via the URL in the browser, for example:

?minilog=true
?minilog=warn
?minilog=chat.warn,radar*.debug

minilog doesn't seem to work in the browser

Upon loading the test/example page jquery_example.html in Chrome (either as a local page or served from a local web server) I see in the console:

Uncaught TypeError: undefined is not a function jquery_example.html:6

When I click the "Add log message", I see in the Chrome console:

Uncaught TypeError: Object #<HTMLInputElement> has no method 'info' jquery_example.html:25

If I comment out the line
var jq = new Minilog.backends.jquery({ url: 'http://localhost:8080/log', interval: 1000, format: 'json' });
and the line

`````` //.pipe(jq)I get a different errorUncaught TypeError: Object # has no method 'emit' minilog.js:15````

Perhaps the instructions are missing steps?

Using redis backend

For the life of me, can't get redis backend to work:
var Minilog=require('minilog'); Minilog.pipe(new Minilog.backends.redis({client:redis,key:key}))
Getting exception:
Unhandled rejection TypeError: dest.emit is not a function at Transform.pipe (C:\...\node_modules\minilog\lib\common\transform.js:28:8) at Function.exports.pipe (C:\...\node_modules\minilog\lib\common\minilog.js:23:14) at Function.module.exports.pipe (C:\...\node_modules\minilog\lib\index.js:21:20)
Am I missing some wrapper? Is there an example of setting up redis backend? Thanks!

Error: Warning: .format() is deprecated in Minilog v2!

Using the Documented example:

var Minilog = require('minilog'),
    consoleBackend = Minilog.backends.nodeConsole;
Minilog.pipe(consoleBackend).format(consoleBackend.formatClean);

I get:
[Error: Warning: .format() is deprecated in Minilog v2! Use .pipe(formatter).pipe(final) instead.]

It isn't clear to me what 'final' should be.

how to send to another node server?

I see how you can send from browser to a log server.

Is there example of sending from one node server to another?
ie, How do I setup a node client to send ?

server filters working?

I modified the themes example to add some filters to block the debug level messages but I can't seem to make them work. Presumably I'm doing something wrong but it seems pretty straightforward so I'm confused. Here's the code:

var log = require('minilog')('app'),
    ConsoleBackend = require('minilog').backends.console;

function out() {
  log
    .debug('debug message')
    .info('info message')
    .warn('warning')
    .error('this is an error message');
};

var minilog = require('minilog');

console.log('\n== Default style\n');

minilog.enable();
var filter = new minilog.Filter();
filter.defaultResult = true;
filter.deny('app','debug');
minilog.pipe(filter);
out();
minilog.disable();
});

and here's the resulting output:

== Default style

app debug debug message
app info info message
app warn warning
app error this is an error message

I also tried just setting defaultResult to false and using allow rules but without success - all the messages seem to come through no matter what I try.

Can I Filter different log levels to different backends.

Given a single Minilog instance can I output all log levels to console, but only warnings and errors to Redis. ie. Can I use separate Filters for different Backends with a single Minilog instance or do I need to create separate Minilog instances for each backend.

turning off coloring?

Some browsers don't support colorization and make the logging difficult to read.

Is there a way to turn off colors?

Docs: Minilog output is suppressed by default.

The readme says "Minilog output is suppressed by default." however in Node this is not the case.

Further if I call enable() then the Formatter I've specified is lost and goes to the default formatter.

Minilog.backends.console.filterEnv breaks in version 2.0.1

I tried to update zendesk/radar to use minilog 2 and discovered that backends.console.filterEnv may have some problem here.

Here is the init statements:

var Minilog = require('minilog');
Minilog
  .pipe(Minilog.backends.console.filterEnv((process.env.radar_log ? process.env.radar_log : '*')))
  .pipe(Minilog.backends.console.formatWithStack)
  .pipe(Minilog.backends.console);

And then it goes with the following error:

<...>/node_modules/radar/node_modules/minilog/lib/common/transform.js:28
  dest.emit('pipe', s);
       ^
TypeError: Object function filter(name, level) {
    return whitelist.some(function(expr) {
      return expr.topic && expr.topic.test(name) && levelMap[level] >= expr.level;
    });
  } has no method 'emit'
    at ConsoleBackend.Transform.pipe (<...>/node_modules/radar/node_modules/minilog/lib/common/transform.js:28:8)
    at Object.<anonymous> (<...>/node_modules/radar/server.js:17:4)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

The offending part would then be filterEnv in lib/node/console.js, and commenting that filter out in Minilog.pipe would render no problems.

A minor mistake in the examples

In your examples, jquery_server.js, is listening to post requests on /log and your jquery_example.html is sending the post request with a parameter.

The switch case is failing because it is listening to /log only and the request it gets is /log?client_id=xxxxxx Took a while to catch it.

Support log.log() to allow injection of Minilog as drop-in replacement of browser and Node console

I love Minilog, And I'd like to use it for an open-source project I'm working on, but I would like to make it optional. The default implementation uses the browser's console, and Node's stdio's console objects for logging.

Problem: both these objects provide a log() that Minilog doesn't provide:

Node     Browser  Minilog
log()    log()    N/A
N/A      N/A      debug()
info()   info()   info()
warn()   warn()   warn()
error()  error()  error()

I know that log.log() isn't pretty, but I think Minilog should offer this method in order to be a drop-in replacement of the console implementations. log() could simply proxy to debug().

If that makes sense to you, I can work on a patch.

minilog license

Hi there!

I wanted to check and ask what license minilog is released under? I can't find one in the usual places (package.json, README.md, or LICENSE.md).

Thank you!

Probem with Minilog & formatters in the Browser

I'm trying to setup Minilog to use in the Browser as follows:

    Minilog
      .pipe(Minilog.suggest)                  // filter
      .pipe(Minilog.backends.browser.color)   // also tried .formatColor
      .pipe(Minilog.backends.browser);        // backend

and get:

Uncaught TypeError: Cannot call method 'emit' of undefined   minilog.js:15

If I leave the above code out I do get basic minilog working ok. I am loading minilog using require.js in case that is relevant.

Update microee dependency

The microee dependency is locked to 0.0.2, which doesn't have a specific license attached to it. This is a bit of a problem when wanting to verify all licenses in a project using minilog. Could you consider bumping up the microee dependency to at least 0.0.3 where the license field was added?

This is related to mixu/microee#2 I just opened - if switching to SPDX-compliant license ID there, it would obviously be great to update the dependency here to that one instead of 0.0.3. Not sure if the functional changes in microee versions > 0.0.3 break this lib then, though :/.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.