Giter Site home page Giter Site logo

js-logger's Introduction

js-Logger Build Status npm version npm dependencies

Lightweight, unobtrusive, configurable JavaScript logger.

logger.js will make you rich, famous and want for almost nothing - oh and it's a flexible abstraction over using console.log as well.

Installation

js-Logger has zero dependencies and comes with AMD and CommonJS module boilerplate. If the last sentence meant nothing to you then just lob the following into your page:

<script src="https://unpkg.com/js-logger/src/logger.min.js"></script>

Have a look at babel-plugin-js-logger, in case your project utilizes Babel, and you want to use js-Logger throughout your entire project efficiently.

Usage

Nothing beats the sheer ecstasy of logging! js-Logger does its best to not be awkward and get in the way. If you're the sort of person who just wants to get down and dirty then all you need is one line of code:

// Log messages will be written to the window's console.
Logger.useDefaults();

Now, when you want to emit a red-hot log message, just drop one of the following (the syntax is identical to the console object)

Logger.debug("I'm a debug message!");
Logger.info("OMG! Check this window out!", window);
Logger.warn("Purple Alert! Purple Alert!");
Logger.error("HOLY SHI... no carrier.");
Logger.trace("Very verbose message that usually is not needed...");
Logger.trace(
  "...containing stack trace (if console.trace() method supports it)"
);

Log messages can get a bit annoying; you don't need to tell me, it's all cool. If things are getting too noisy for your liking then it's time you read up on the Logger.setLevel method:

// Only log WARN and ERROR messages.
Logger.setLevel(Logger.WARN);
Logger.debug("Donut machine is out of pink ones"); // Not a peep.
Logger.warn("Asteroid detected!"); // Logs "Asteroid detected!", best do something about that!

// Ah, you know what, I'm sick of all these messages.
// But I want to see them again later
var oldLevel = Logger.getLevel();
Logger.setLevel(Logger.OFF);
Logger.error("Hull breach on decks 5 through to 41!"); // ...

// Actually, maybe those logs were quite useful...
Logger.setLevel(oldLevel);

Log Handler Functions

All log messages are routed through a handler function which redirects filtered messages somewhere. You can configure the handler function via Logger.setHandler noting that the supplied function expects two arguments; the first being the log messages to output and the latter being a context object which can be inspected by the log handler.

Logger.setHandler(function (messages, context) {
  // Send messages to a custom logging endpoint for analysis.
  // TODO: Add some security? (nah, you worry too much! :P)
  jQuery.post("/logs", { message: messages[0], level: context.level });
});

Default Log Handler Function

js-Logger provides a default handler function which writes to your browser's console object using the appropriate logging functions based on the message's log level (ie: Logger.info() will result in a call to console.info()). The default handler automatically shims for sub-optiomal environments right down to IE7's complete lack of console object (it only appears when you open the DevTools - seriously, this is one of the anti-user troll things I've seen!)

Use Logger.createDefaultHandler() to return a new log handler function which can then be supplied to Logger.setHandler().

You can customise the formatting of each log message by supplying a formatter function to createDefaultHandler:

Logger.createDefaultHandler({
  formatter: function (messages, context) {
    // prefix each log message with a timestamp.
    messages.unshift(new Date().toUTCString());
  },
});

You can use functional composition to extend the default handler with your own custom handler logic:

var consoleHandler = Logger.createDefaultHandler();
var myHandler = function (messages, context) {
  jQuery.post("/logs", { message: messages[0], level: context.level });
};

Logger.setHandler(function (messages, context) {
  consoleHandler(messages, context);
  myHandler(messages, context);
});

useDefaults

Logger.useDefaults() is a convenience function which allows you to configure both the default logLevel and handler in one go:

Logger.useDefaults({
  defaultLevel: Logger.WARN,
  formatter: function (messages, context) {
    messages.unshift(new Date().toUTCString());
  },
});

You can also use the alias Logger.setDefaults().

Named Loggers

Okay, let's get serious, logging is not for kids, it's for adults with serious software to write and mission critical log messages to trawl through. To help you in your goal, js-Logger provides 'named' loggers which can be configured individual with their own contexts.

// Retrieve a named logger and store it for use.
var myLogger = Logger.get("ModuleA");
myLogger.info("FizzWozz starting up");

// This logger instance can be configured independent of all others (including the global one).
myLogger.setLevel(Logger.WARN);

// As it's the same instance being returned each time, you don't have to store a reference:
Logger.get("ModuleA").warn("FizzWozz combombulated!");

Note that Logger.setLevel() will also change the current log filter level for all named logger instances; so typically you would configure your logger levels like so:

// Create several named loggers (typically in their own module)
var loggerA = Logger.get("LoggerA");
var loggerB = Logger.get("LoggerB");
var loggerC = Logger.get("LoggerC");

// Configure log levels.
Logger.setLevel(Logger.WARN); // Global logging level.
Logger.get("LoggerB").setLevel(Logger.DEBUG); // Enable debug logging for LoggerB
Logger.get("LoggerC").setLevel(Logger.TRACE); // Enable trace logging for LoggerC

Profiling

Sometimes its good to know what's taking so damn long; you can use Logger.time() and Logger.timeEnd() to keep tabs on things, the default log handler implementation delegates to the equivalent console methods if they exist, or write to console.log if they don't.

// Start timing something
Logger.time("self destruct sequence");

// ... Some time passes ...

// Stop timing something.
Logger.timeEnd("self destruct sequence"); // logs: 'self destruct sequence: 1022ms'.

Note that time and timeEnd methods are also provided to named Logger instances.

Usage with TypeScript

TypeScript is great, you should use it. See the typescript consumer test for example usage.

js-logger's People

Contributors

aintaer avatar ajwagner777 avatar benjaminvadant avatar biergit avatar bronzehedwick avatar chrsmith avatar coreprocess avatar corvofeng avatar creynders avatar ddanila avatar dependabot[bot] avatar dionnis avatar harrisrobin avatar james-west avatar jonny-improbable avatar jonnyreeves avatar jsyrjala avatar mutsys avatar redpoptarts avatar scevallos avatar stasberkov avatar tanneess avatar timaebi avatar timm-gs 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

js-logger's Issues

export ILogger interface

Hello,

we are using your component and find it a very handy component. But we use VueJS in combination of typescript. And it is a petty that you do not export the ILogger interface in your logger.d.ts

Now we use a any object, and it would be nice to have the ilogger interface available for better typescript.

Thanks

Feature Request - Logger.getLevel

Hi,

it would be nice if there was a method that returns the current level of the logger.

This would allow to change temporarily the level and then get back to a previous value.

For example :

let level = Logger.getLevel()
Logger.setLevel(Logger.OFF)
//do stuff you don't want to log
Logger.setLevel(level) //get back to the previous level

I have added this functionnality (see my pull request)

Ben

Inconsistent string interpolation

I'm sure this is likely an issue with the way I've set things up (latest node, bable, webpack, ) but I cannot get string interpolation to work when using Logger.get. ex:

import Logger from 'js-logger'

Logger.useDefaults()
Logger.warn('TEST')
Logger.warn('TEST %sPOLATED', 'INTER')
const log = Logger.get('Log')
log.warn('Test')
log.warn('TEST %sPOLATED', 'INTER')

Will output:

TEST
TEST INTERPOLATED
[Log] Test
[Log] TEST %sPOLATED INTER

So what am I not understanding here?

In addition, if I do not use Logger.useDefaults(), for example by replacing that line with Logger.setLevel(Logger.INFO), I won't see any logs at all. Any thoughts as to why this occurs?

log levels

Hi i just checked the code and i like the logger :)

My question is: would it be more common to use the standard log levels like BSD syslog levels?

There is a rfc: https://tools.ietf.org/html/rfc3164#section-4.1.2 (Page 8, last lines) Log level 0 - 7 for the severity.

           0       Emergency: system is unusable
           1       Alert: action must be taken immediately
           2       Critical: critical conditions
           3       Error: error conditions
           4       Warning: warning conditions
           5       Notice: normal but significant condition
           6       Informational: informational messages
           7       Debug: debug-level messages

If you agree i can fork it if you like and send a pull request.

Kind regards

no line number output in log message

It would be nice to support line numbers in the debug-panel.
The native window.console shows line numbers and are clickable to the destination.

npm package 1.4.1 has different code from github

Hello,
I've noticed that the js-logger source code get by npm install js-logger has different code from the githoub. The nuget package and the github have the same version 1.4.1. Calling the Logger.trace("Some log") cause error because this function not exists in npm package.

Regards

Uncaught TypeError: Cannot read properties of undefined (reading 'Logger')

Uncaught TypeError: Cannot read properties of undefined (reading 'Logger')
    at logger.min.js:1:2713
    at logger.min.js:1:2789

How I'm using it:

In my js file, I have import * as Logger from './logger.min.js'; Logger.useDefaults();
Then, I call Logger.info("test123").

What could I be doing wrong?

Logger.debug output

Chrome (I'm on v.54) have some usefull filters (log, info, debug...)
Logger.log() output in log filter
but Logger.debug() don't output in debug filter

How do I extend the logger?

By default, Logger.get() returns ILogger which is only good for calling the particular logging methods. As far as I found, I can't even set some additional values to the context.

What is the proper "entry point" if I want to extend js-logger, like adding additional error levels, logging methods for the new levels, wrapping or overriding the base methods, while having it (hopefully) strongly typed?

Support console colors

Chrome and Firefox both support colors in console. For example:

console.log('%c console colors', 'background: black; color: yellow');

js-logger should be able to pass this through to the underlying console implementation (as they are just additional parameters).

setLevel(Logger.OFF) not working

I have the following but the log still get printed out:

var logger = Logger.get('BaseComponent');
Logger.get('BaseComponent').setLevel(Logger.OFF);
logger.setLevel(Logger.OFF);

yarn?

>yarn add js-Logger

yarn add v1.22.4
[1/4] Resolving packages...
error An unexpected error occurred: "https://registry.yarnpkg.com/js-Logger: Not found".

Request for tables

Could it be possible to integrate tables into the project? It'd be nice to look at some of my reference data in a well presented way.

Add Support for Cascading LogLevel Configuration

JSLogger should cascade the LogLevel configuration for named loggers based on their namespace, so for example:

var loggerA = Logger.get("parentNS.clientA");

// Configure the LogLevel of the parent namespace
Logger.get("parentNS").setLevel(Logger.WARN);

loggerA.info("Info Message"); // No output
loggerA.warn("Warning Message"): // Logs "Warning Message"

This feature would provide developers a way to express log levels for an entire group of clients without having to manually list them all out.

Question : stack trace

When using default console, we can see where in our code there is this log (error whatever)
but since this plugin use Function.prototype.apply.call(hdlr, console, messages);
all logs are from logger.js:181

So, is there a way to see where is our log from ?

How to remove stacktrace from trace logs?

I like 3 levels of logging. Info for general information. Debug for more debug items. And trace for a lot of logs like all streaming messages. In js-logger, the Logger.trace also logs a stacktrace. This is too much information and I don't need it specifically.

Can you disable the stacktrace logging in Logger.trace?

Log Handler for Splunk

Splunk Http Event Logging requests authentication to be sent during POST request via headers.

Something likes:
"headers": {"authorization": "Splunk {token}"

How can this be done using js-logger?

Logger.setHandler improvement

Hi!

var myHandler = function(messages, context){
//send log to server e.t.c
}
Logger.setHandler(function (messages, context) {
    myHandler(messages, context);
    //And now i want to define parent handler implementation. How can I do it?
});

How to use with require or import?

Can you add to the README how to use the Logger without adding a <script> tag in the HTML but rather using it as a module with require or import statements?
So it isn't added to the global namespace.

Logging into plain text files

Hi,
I was wondering if this library provides logging data into plain text files instead of the regular web console.

The idea is that if we could log onto separate files, we could have a look at them at our own leisure, let alone send them over to someone for debugging.

I was expecting something like -
var myLogger = new Logger('/path/to/txt/file/where/data/will/be/logged')

As per the above line, all logs will be saved onto that file. If the file doesn't already exist, a new file will be created.

Thanks in advance,
Ashish Deshpande

Request for giving access to time variable in Logger.timeEnd()

I am currently using

logger.time('Powers Fetched');
setTimeout(() => {
    ...
    logger.timeEnd('Powers Fetched');
}, 1500);

but it gives me ugly decimal numbers like 1514.76513671875ms

My proposal is to give us access to the time variable, maybe as a callback as second paramter or an optional config object, so we can set the decimal points, change unit, etc. If something like this already exists, please shed some light on it.

Formatting example breaks console substition

  formatter: function (messages, context) {
    // prefix each log message with a timestamp.
    messages.unshift(new Date().toUTCString());
  },
});

will break: logger.log('Hello %s', 'Jonny')

logger.debug('...') calls don't work when level is set to logger.DEBUG

logger.debug('...') calls are NOT printed when level is set to logger.DEBUG when using v1.4.1.
logger.info('...') and above are printed.
With v1.3.0 it works fine.

This is the basic functionality of a logger, if this doesn't work than it's pretty much useless :P

For the project where I'm using it I'm writing my code in TypeScript and compiling it with latest version of webpack, it might be relevant.
Will be using v1.3.0 until this issue is resolved.

Thanks!

setLevel(String)

I'm trying to set the log level based on configuration coming from the backend. The backend value is a String: debug, info, warn, error, OFF.
setLevel(String) isn't supported. Am I missing something obvious? Any alternative suggestions?

I suppose I could switch based on the config value and call the corresponding setValue(Level) call.

Declaration file not recognized by typescript compiler

I'm using typescript 2.3.4. When I declare a triple-slash directive pointing to logger.d.ts:

/// <reference path="../node_modules/js-logger/src/logger.d.ts" />

and write Logger in my source file, the compiler doesn't recognize it and throws the following error:

error TS2304: Cannot find name 'Logger'.

logLevel typo in README.md

README suggests this:

Logger.useDefaults({
    logLevel: Logger.WARN,
    formatter: function (messages, context) {
        messages.unshift('[MyApp]');
        if (context.name) messages.unshift('[' + context.name + ']');
    }
})

However logLevel property should be defaultLevel according to the code.

Messages Threshold

Hi,

Is there any Threshold method in js-logger? or an event that tells me this is the last message or something?

I want to set the handler to send messages to a WS endpoint, but not in every message I have, I want to more that more optimized so I thought about a threshold, something like threshold=5 so after the 5th message I send the array of messages to the server then reset the array...

Thanks.

setLevel doesn't seem to work

This code in a Vue 3 store (using webpack, not using typescript):

  import jsLogger from 'js-logger';

  const log = jsLogger.get('SettingsStore');
  log.info('Named Settings logger level set to ' + JSON.stringify(log.getLevel()));
  log.info('Debug enabled: ' + log.enabledFor(jsLogger.DEBUG));
  log.debug('Test debug message');

doesn't log the last message:

[SettingsStore] Named Settings logger level set to {"value":1,"name":"TRACE"}
[SettingsStore] Debug enabled: true

I am new to ES6 & mocules, I must be missing something obvious??

Changing the last line to log.info outputs the message... what am I missing?

This is what I have in package.json:

"js-logger": "^1.6.1",

Create a method for setHandler and useDefaults

I'm using this to log on the server and client and need to duplicate a bit of the useDefaults function in a setHandler function (to send back to the browser console). It would be nice if this was doable from the library itself.

Debug Level Not Showing Up

Hi, I tried many things but DEBUG level is not shown for some reason. My configuration:

//Logger.useDefaults();
Logger.useDefaults({
    defaultLevel: Logger.DEBUG,
    formatter: function (messages, context) {
        messages.unshift(new Date().toUTCString())
    }
});

Logger.setLevel(Logger.DEBUG);

// Only log WARN and ERROR messages.
//Logger.setLevel(Logger.WARN);
//Logger.debug("Donut machine is out of pink ones");  // Not a peep.
//Logger.warn("Asteroid detected!");  // Logs "Asteroid detected!", best do something about that!

// Ah, you know what, I'm sick of all these messages.
// But I want to see them again later
//var oldLevel = Logger.getLevel();
//Logger.setLevel(Logger.OFF);
//Logger.error("Hull breach on decks 5 through to 41!");  // ...

// Actually, maybe those logs were quite useful...
//Logger.setLevel(oldLevel);

Logger.debug("I'm a debug message!");
Logger.info("OMG! Check this window out!", window);
Logger.warn("Purple Alert! Purple Alert!");
Logger.error("HOLY SHI... no carrier.");

Logger.debug("XXXXXXXX");
Logger.debug("YYYYYYYY");

// Start timing something
Logger.time('self destruct sequence');

// ... Some time passes ...

// Stop timing something.
Logger.timeEnd('self destruct sequence'); // logs: 'self destruct sequence: XXXms'.

When logging the line number comes from the logger instead the file where the logger is used

I 'm using the js-logger in my project, but as you can see in the below logging records , the line number is referring to a line number in the logger.js file .

how can I get the line number of the file where the logging is enabled?

`
DEBUG-Wed, 02 Oct 2019 09:19:46 GMT Desk polling done at Wednesday, October 2nd 2019, 11:19:46 am logger.js:188

DEBUG-Wed, 02 Oct 2019 09:19:49 GMT Desk polling done at Wednesday, October 2nd 2019, 11:19:49 am logger.js:188 `

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.