Code Monkey home page Code Monkey logo

meteor-logger-console's Introduction

support support

Logging: To Console

Console adapter for logger driver. Print Client's log messages to Server's console package. All messages is enhanced with colors and extra styles for better readability.

This package is not limited to transferring Client log messages to Server. It can be used on Client or Server only, or for printing colorized messages.

Features:

  • ๐Ÿ’ช Flexible log level filters;
  • ๐Ÿ‘จโ€๐Ÿ’ป userId is automatically passed and logged, data is associated with logged-in user;
  • ๐Ÿ“Ÿ Pass logs from Client right to Server's console;
  • ๐Ÿ•ท Catch all browser's errors and exceptions.

Screen shots:

Server: server example

Client: client example

Installation:

meteor add ostrio:logger # If not yet installed
meteor add ostrio:loggerconsole

ES6 Import:

import { Logger } from 'meteor/ostrio:logger';
import { LoggerConsole } from 'meteor/ostrio:loggerconsole';

Usage

Initialize LoggerConsole instance passing LoggerInstance as a first argument into constructor to enable logging into the console.

Initialization [Isomorphic]

new LoggerConsole(LoggerInstance, settings)

  • LoggerInstance {Logger} - from new Logger()
  • settings {Object}
  • settings.highlight {Boolean} - Enable/Disable color highlighting; By default: true
  • settings.format {Function} - This function must return String. Arguments:
    • opts {Object}
    • opts.userId {String}
    • opts.time {Date} - Report date
    • opts.level {String} - Message level, one of: ERROR, FATAL, WARN, DEBUG, INFO, TRACE, LOG, *
    • opts.message {String} - Report message
    • opts.data {Object} - Additional info passed as object

Example: [Isomorphic]

import { Logger } from 'meteor/ostrio:logger';
import { LoggerConsole } from 'meteor/ostrio:loggerconsole';

// Initialize Logger:
const log = new Logger();
// Initialize and enable LoggerConsole with default settings:
(new LoggerConsole(log)).enable();

// Initialize and enable LoggerConsole with custom formatting:
(new LoggerConsole(log, {
  format(opts) {
    return ((Meteor.isServer) ? '[SERVER]' : '[CLIENT]') + ' [' + opts.level + '] - ' + opts.message;
  }
})).enable();

Activate with custom adapter settings: [Isomorphic]

import { Logger } from 'meteor/ostrio:logger';
import { LoggerConsole } from 'meteor/ostrio:loggerconsole';

const log = new Logger();
(new LoggerConsole(log)).enable({
  enable: true,
  filter: ['ERROR', 'FATAL', 'WARN'], /* Filters: 'ERROR', 'FATAL', 'WARN', 'DEBUG', 'INFO', 'TRACE', '*' */
  client: true, // Set to `false` to avoid log transfer from Client to Server
  server: true  // Set to `false` to disallow execution on Server
});

Log message: [Isomorphic]

import { Logger } from 'meteor/ostrio:logger';
import { LoggerConsole } from 'meteor/ostrio:loggerconsole';

const log = new Logger();
(new LoggerConsole(log)).enable();

/*
  message {String} - Any text message
  data    {Object} - [optional] Any additional info as object
  userId  {String} - [optional] Current user id
 */
log.info(message, data, userId);
log.debug(message, data, userId);
log.error(message, data, userId);
log.fatal(message, data, userId);
log.warn(message, data, userId);
log.trace(message, data, userId);
log._(message, data, userId); // Shortcut

// Use with throw
throw log.error(message, data, usmerId);

Catch-all Client's errors example: [Client]

/* Store original window.onerror */
const _GlobalErrorHandler = window.onerror;

window.onerror = function (msg, url, line) {
  log.error(msg, {file: url, onLine: line});
  if (_GlobalErrorHandler) {
    _GlobalErrorHandler.apply(this, arguments);
  }
};

Catch-all Server's errors example: [Server]

const bound = Meteor.bindEnvironment((callback) => {callback();});
process.on('uncaughtException', function (err) {
  bound(() => {
    log.error('Server Crashed!', err);
    console.error(err.stack);
    process.exit(7);
  });
});

Catch-all Meteor's errors example: [Server]

// store original Meteor error
const originalMeteorDebug = Meteor._debug;
Meteor._debug = function (message, stack) {
  const error = new Error(message);
  error.stack = stack;
  log.error('Meteor Error!', error);
  return originalMeteorDebug.apply(this, arguments);
};

Use multiple logger(s) with different settings: [Isomorphic]

const log1 = new Logger();
const log2 = new Logger();

(new LoggerConsole(log1)).enable({
  filter: ['*'],
  client: true,
  server: true
});

(new LoggerConsole(log2)).enable({
  filter: ['ERROR', 'FATAL'],
  client: true,
  server: true
});

Running Tests

  1. Clone this package
  2. In Terminal (Console) go to directory where package is cloned
  3. Then run:

Meteor/Tinytest

meteor test-packages ./

Support this awesome package:

Support our open source contribution:

meteor-logger-console's People

Contributors

dr-dimitru avatar faburem avatar fawzisf avatar

Stargazers

 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

meteor-logger-console's Issues

Meteor 1.3

When I done update on Meteor 1.3 version errors came:

Exception while invoking method 'sendProfile' {
stack: 'TypeError: Cannot call method 'substring' of undefined\n
at [object Object].Debug.trace (C:\Users~\AppData\Local.meteor\packages\ostrio_loggerconsole\1.0.0\npm\node_modules\console-debug\debug.js:97:41)\n
at [object Object].Debug.debug (C:\Users~\AppData\Local.meteor\packages\ostrio_loggerconsole\1.0.0\npm\node_modules\console-debug\debug.js:157:8)\n
at Object.Package (packages\ostrio_loggerconsole.js:77:21)\n
at Logger.logit (packages\ostrio_logger.js:92:14)\n
at Logger.debug (packages\ostrio_logger.js:214:17)\n
at [object Object].sendHandymanProfile (server/methods.js:10:16)\n
at [object Object].methodMap.(anonymous function) (packages\meteorhacks_kadira.js:2586:30)\n
at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1704:12)\n
at packages/ddp-server/livedata_server.js:711:19\n
at [object Object]._.extend.withValue (packages\meteor.js:1100:17)',
I20160330-13:33:00.946(3)? source: 'method' }

Reinstallation doesn't help, something wrong with packages\ostrio_loggerconsole\1.0.0\npm\node_modules\console-debug\debug.js:97:41

var completeMessage = "",
            format = dateFormat(new Date(), 'HH:MM:ss'),
            func = undefined,
            appDir = path.dirname(require.main.filename),
            p = this.get_file_parent();

        if(type != "ERROR"){
            if (p) {
                var parentfile = p.split(appDir)[1].substring(1); // HERE BUG
                func = " @ "+parentfile+":"+this.get_line_parent();
            } else {
                return;
            }
        }

Exception if data is null

There is an exception thrown when I am trying to log information with data = null.
Example of code with error:

     log.info('Some message', null, Meteor.userId());

This code results in exception in line 162.

      if (helpers.isString(data.stackTrace)) {      // <= The wrong line
        data.stackTrace = data.stackTrace.split(/\n\r|\r\n|\r|\n/g);
      }

I believe it's necessary to add a check and the code should be like:

      if (data && helpers.isString(data.stackTrace)) {   
       // ....

PS
The simple solution is to use undefined or {} as data.

Avoid Json showing up?

Hi,

Is there anyway to avoid json data to be shown in console? I'm using logger-mongo, logger-file and logger-console (yeah, I know, what a f*****g paranoid) and it's great to have that data saved in the mongo collection, but it's becoming a problem to have it shown in the console also.

Any option to avoid it?

Thanks!

Option to disable formatting on console logs [FEATURE SUGGESTION]

I have a suggestion:

  • Provide a flag to disable formatting on messages
  • When reading logs in Elasticsearch, Kibana, we can see the color tags in of the logs. The formatting doesn't help us there however the other functionality (timestamps, message types, etc.) do help us. To clean up logs, I'd like to remove any color, styling etc. settings and I have made a rudimentary branch where setting disableFormatting=true allows different conditional blocks to trigger where no coloring, boldness etc. is applied to messages.

Please let me know what you think.

Data always shows, even when empty

Hi,

Thank you for this great package. I have a suggestion/issue.

The data param is always showing up on the browser console, even when it's empty, which is a bit annoying.

image

The data param always gets added after the format, regardless of what you put in the format. So if you print the data in the format it will show up twice. Example:

image

This is a bit of a different behavior compared to the server console where the data is only printed if you specify it directly in the format.

I actually like that the data is added to the browser console since the browser renders it nicely, but ideally I would like to have more control over this.

So my suggestions are:

  1. When data is empty don't show it in the console log, that way we avoid seeing the clutter for "Object {}".
  2. Add an additional setting where you can toggle it on/off completely. That way if you want to do a custom render of the data you do it in the format and can avoid it showing up twice.

Method '1_logger_emit_Console' not found

With the code:

import { Logger }        from 'meteor/ostrio:logger';
import { LoggerConsole } from 'meteor/ostrio:loggerconsole';

// Initialize Logger:
const mylog = new Logger();
// Initialize and enable LoggerConsole with default settings:
(new LoggerConsole(mylog)).enable();

export function log(level,message)
{
    console.log('['+level+'] ',message);
    mylog.info('message',{},'');

}

I get the log message in the browser, but always with the error:

Error invoking Method '1_logger_emit_Console': Method '1_logger_emit_Console' not found [404]

What is wrong?!

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.