Skip to content

Instantly share code, notes, and snippets.

@bryanforbes
Last active December 16, 2015 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryanforbes/5460120 to your computer and use it in GitHub Desktop.
Save bryanforbes/5460120 to your computer and use it in GitHub Desktop.
/// ice/logging/advanced.js
define(function (require, exports) {
exports.log = function (message, options) {
// ...
};
exports.error = function (message, options) {
// ...
};
});
// ice/assert.js
define(function (require) {
var logger = require('./logging');
return function (condition, text, custom) {
if (condition) {
return;
}
if (typeof text !== 'string') {
custom = text || custom || null;
text = null;
}
return logger.error(text, {
name: 'assert',
condition: condition,
custom: custom,
exception: new Error('LOG')
});
};
});
// ice/logging/console.js
define(function () {
return console;
});
// ice/logging/loader.js
define(function (require, exports, module) {
var defaultLogger = module.config().logger || './console';
exports.load = function (id, parentRequire, loaded) {
var require = id.indexOf('./') === 0 ? parentRequire : require;
require(id, loaded);
};
});
// ice/logging.js
define(function (require) {
return require('./loader!');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample</title>
</head>
<body>
<script src="dojo/dojo.js"></script>
<script>
require({
config: {
'ice/loader': {
logger: 'ice/logging/advanced'
}
}
}, ['ice/assert'], function (assert) {
// when assert is used, it uses the advanced
// logging facilities
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample</title>
</head>
<body>
<script src="dojo/dojo.js"></script>
<script>
require(['ice/assert'], function (assert) {
// when assert is used, it uses the native
// console object for logging
});
</script>
</body>
</html>
@rcgill
Copy link

rcgill commented Apr 26, 2013

Excellent example of how to solve the problem at hand as well as demonstrate a powerful AMD idiom.

In this case, I think it could be simplified by configuring the module ice/logging/loader and then require that module instead of ice/logging in ice assert. This would eliminate the logging module.

@uhop
Copy link

uhop commented Apr 26, 2013

Very cool! Essentially it shows how to masquerade a logging facility as a primordial console object, and how to switch between them rather seamlessly. Besides the ability to use a basic logging practically for free, demonstrates the other side of the coin: it allows to retrofit an existing code with a flexible logging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment