Skip to content

Commit

Permalink
Merge pull request #31 from jonnyreeves/feature/extract-default-handler
Browse files Browse the repository at this point in the history
Extract default handler
  • Loading branch information
jonnyreeves authored Jul 5, 2016
2 parents 2b5bc66 + 0906f8d commit 073ef21
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 22 deletions.
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
## 1.3.0 (5th July, 2016)
- Add `Logger.createDefaultHandler()`, fixes #26
- Correct typo in README, fixes #28
- Adds Typescript definitions (`logger.d.ts`), (#27, @pjsb)

## 1.2.0 (10 September, 2015)
- Support for custom message formatter in Logger.useDefaults()
- Support for custom message formatter in Logger.useDefaults()
- Logger.useDefaults() now expects a hash instead of a logLevel.

## 1.1.1 (14th July, 2015)
Expand Down
40 changes: 35 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,45 @@ Logger.setHandler(function (messages, context) {
```

### Default Log Handler Function
When you invoke `Logger.useDefaults()`, you can specify a default LogLevel and a custom
logFormatter function which can alter the messages printed to the console:
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 - seriosuly, 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 `createDefaultLogHandler`:

```js
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:

```js
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:

```js
Logger.useDefaults({
logLevel: Logger.WARN,
defaultLevel: Logger.WARN,
formatter: function (messages, context) {
messages.unshift('[MyApp]');
if (context.name) messages.unshift('[' + context.name + ']');
messages.unshift(new Date().toUTCString())
}
})
```
Expand Down
2 changes: 1 addition & 1 deletion bower.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "js-logger",
"version": "1.2.0",
"version": "1.3.0",
"main": "src/logger.js",
"ignore": [
"**/.*",
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "js-logger",
"version": "1.2.0",
"version": "1.3.0",
"description": "Lightweight, unobtrusive, configurable JavaScript logger",
"author": "Jonny Reeves (http://jonnyreeves.co.uk)",
"homepage": "http://github.com/jonnyreeves/js-logger",
Expand All @@ -20,7 +20,8 @@
],
"main": "src/logger.js",
"scripts": {
"test": "gulp test lint"
"test": "gulp test lint",
"build": "gulp default"
},
"devDependencies": {
"gulp": "~3.8.11",
Expand Down
31 changes: 19 additions & 12 deletions src/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
var Logger = { };

// For those that are at home that are keeping score.
Logger.VERSION = "1.2.0";
Logger.VERSION = "1.3.0";

// Function which handles all incoming log messages.
var logHandler;
Expand Down Expand Up @@ -159,9 +159,10 @@
(contextualLoggersByNameMap[name] = new ContextualLogger(merge({ name: name }, globalLogger.context)));
};

// Configure and example a Default implementation which writes to the `window.console` (if present). The
// `options` hash can be used to configure the default logLevel and provide a custom message formatter.
Logger.useDefaults = function(options) {
// CreateDefaultHandler returns a handler function which can be passed to `Logger.setHandler()` which will
// write to the window's console object (if present); the optional options object can be used to customise the
// formatter used to format each log message.
Logger.createDefaultHandler = function (options) {
options = options || {};

options.formatter = options.formatter || function defaultMessageFormatter(messages, context) {
Expand All @@ -171,11 +172,6 @@
}
};

// Check for the presence of a logger.
if (typeof console === "undefined") {
return;
}

// Map of timestamps by timer labels used to track `#time` and `#timeEnd()` invocations in environments
// that don't offer a native console method.
var timerStartTimeByLabelMap = {};
Expand All @@ -185,8 +181,12 @@
Function.prototype.apply.call(hdlr, console, messages);
};

Logger.setLevel(options.defaultLevel || Logger.DEBUG);
Logger.setHandler(function(messages, context) {
// Check for the presence of a logger.
if (typeof console === "undefined") {
return function () { /* no console */ };
}

return function(messages, context) {
// Convert arguments object to Array.
messages = Array.prototype.slice.call(messages);

Expand Down Expand Up @@ -227,7 +227,14 @@
options.formatter(messages, context);
invokeConsoleMethod(hdlr, messages);
}
});
};
};

// Configure and example a Default implementation which writes to the `window.console` (if present). The
// `options` hash can be used to configure the default logLevel and provide a custom message formatter.
Logger.useDefaults = function(options) {
Logger.setLevel(options && options.defaultLevel || Logger.DEBUG);
Logger.setHandler(Logger.createDefaultHandler(options));
};

// Export to popular environments boilerplate.
Expand Down
2 changes: 1 addition & 1 deletion src/logger.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 073ef21

Please sign in to comment.