jonnyreeves/js-logger

Create a method for setHandler and useDefaults

Closed this issue · 7 comments

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.

+1 I need this functionality as well.

Hey Guys, could you please provide a little more detail on what feature you are after? Would pulling the default logHandler out into a member property be sufficient, ie:

Logger.defaultHandler = function (messages, context) { ... };

My use case is to customize the message that gets printed out. For example, I always want the project name to be prepended to each log statement.

[MyProject] This is log statement
[MyProject] [ModuleA] This is a log statement from a named logger

@jonnyreeves For my case, I think it would be better if the message handling part of exposed instead:

// Prepend the logger's name to the log message for easy identification.
if (context.name) {
    messages[0] = "[" + context.name + "] " + messages[0];
}

So my current train of thought is that useDefaults could be made a little more flexible when it comes to how the log messages are actually formatted - this would probably solve 80% of use-cases. To enable this, I am thinking of creating the following API:

Logger.useDefaults = function(options) {
        options = merge(options, {
            // Messages under this log level will not be written.
            defaultLevel: Logger.DEBUG,

            // Specify the format of log messages written to the console.  This string should be
            // made up using the following tokens:
            //   {{name}} The name of the logger.
            //   {{message}} The log message(s).
            //   {{timestamp}} timestamp when the log message is emitted
            //   {{level}} logLevel of the message as a string (ie: INFO).
            logFormat: "[{{name}}] {{message}}",

            // Will be invoked whenever a timestamp is required by the logFormat.
            formatTimestamp: function () { return new Date.toString() },
        });

So in @khirakawa's example, he could use:

Logger.useDefaults({
    logFormat: "[MyProject] [{{name}}] {{messages}}"
});

I would expose the logFormatter on Logger.utils.formatter so other, more bespoke log handlers, can also leverage it.

I'll try and knock some code together over the next few days and put it up for review, please let me know your thoughts if you have an opinion :)

@jonnyreeves yes, that would work perfectly for my use case. Thanks!

@jonnyreeves I'm also using js-logger to log on the client and server and I'd like to know if you're going to include the addition from @khirakawa

Fixed in v1.2.0; you can now supplied a formatter function to useDefaults and mutate the messages Array as you see fit.