angular-logger
v1.3.2
Published
> Enhance $log for better logging, including patterns and level management
Downloads
393
Maintainers
Readme
#angular-logger
logEnhancerProvider.prefixPattern = '%s::[%s]>';
logEnhancerProvider.datetimePattern = 'dddd h:mm:ss a';
logEnhancerProvider.logLevels = {
'*': logEnhancerProvider.LEVEL.OFF,
'main': logEnhancerProvider.LEVEL.WARN,
'main.subB': logEnhancerProvider.LEVEL.TRACE
};
$log.getInstance('banana').info('Hello World!'); // ignored, logging turned off for '*'
$log.getInstance('main.subA').info('Hello World!'); // ignored, doesn't pass logging threshold of 'main'
$log.getInstance('main.subB').trace('Hello World!'); // 17-5-2015 11:52:52::[main.subB]> Hello World!
$log.getInstance('main.subB').info('Hello %s!', 'World', { 'extra': ['pass-through params'] });
// 17-5-2015 11:53:51::[main.subB]> Hello World! Object { "extra": "pass-through params"}
###WORKING DEMO
- About
- Installing - Bower - Manually
- Getting Started
- Applying Patterns - Prefix pattern - Datetime stamp patterns - Logging patterns
- Managing logging priority
This library enhances $log
's logging capabilities. It works by modifying the arguments going into the original functions. Although you can configure patterns and logging level priorities, it also simply works as a simple drop-in (demo).
- Enhances Angular's
$log
service so that you can define separate contexts to log for, where the output will be prepended with the context's name, a datetime stamp and can be furter expanded to include the logging level. - Further enhances the logging functions so that you can apply patterns eliminatinging the need of manually concatenating your strings
- Introduces log levels, where you can manage logging output per context or even a group of contexts
- Works as a complete drop-in replacement for your current
$log.log
orconsole.log
statements - original post
angular-logger has optional dependencies on momentjs and sprintf.js: without moment you can't pattern a nicely readable datetime stamp and without sprintf you can't pattern your logging input lines. Default fixed patterns are applied if either they are missing.
bower install angular-logger --save
npm install angular-logger --save
Include angular-logger.js, momentjs and sprintf.js in your web app.
After installing, add the
angular-logger
module as a dependency to your module:angular.module('YourModule', ['angular-logger'])
Start logging for your context
app.controller('LogTestCtrl', function ($log) { var normalLogger = $log.getInstance('Normal'); var mutedLogger = $log.getInstance('Muted'); $log.logLevels['Muted'] = $log.LEVEL.OFF; this.doTest = function () { normalLogger.info("This *will* appear in your console"); mutedLogger.info("This will *not* appear in your console"); } });
By default, the prefix is formatted like so (if sprintf.js is present):
datetime here::[context name here]>your logging input here
// if sprintf.js is missing, angular-logger defaults back to a fixed pattern that does include the used loglevel:
datetime here::context name here::loglevel used here>your logging input here
However, you can change this as follows:
app.config(function (logEnhancerProvider) {
logEnhancerProvider.prefixPattern = '%s - %s: ';
});
app.run(function($log) {
$log.getInstance('app').info('Hello World');
});
// was: Sunday 12:55:07 am::[app]>Hello World
// became: Sunday 12:55:07 am - app: Hello World
And if you add another prefix-placeholder %s
, you get the log level as well:
logEnhancerProvider.prefixPattern = '%s - %s - %s: '; // Sunday 12:55:07 am - app - info: Hello World
You can also remove it completely, or have just the datetime stamp or just the context prefixed:
// by the power of sprintf!
logEnhancerProvider.prefixPattern = '%s - %s: '; // both
logEnhancerProvider.prefixPattern = '%s: '; // timestamp
logEnhancerProvider.prefixPattern = '%1$s: '; // timestamp by index
logEnhancerProvider.prefixPattern = '%2$s: '; // context by index
logEnhancerProvider.prefixPattern = '%2$s - %1$s: '; // both, reversed
logEnhancerProvider.prefixPattern = '%3$s: '; // logging level by index
logEnhancerProvider.prefixPattern = '%3$s - %2$s - %1$s: '; // loglevel, context and timestamp reversed
This works because angular-logger will use three arguments context, timestamp and loglevel for the prefix, which can be referenced by index.
If you have included moment.js in your webapp, you can start using datetime stamp patterns with angular-logger. The default pattern is LLL
, which translates to a localized string that matches the current user's Locale. You customize the pattern as follows:
app.config(function (logEnhancerProvider) {
logEnhancerProvider.datetimePattern = 'dddd';
});
app.run(function($log) {
$log.getInstance('app').info('Hello World');
});
// was: Sunday 12:55:07 am::[app]>Hello World
// became: Sunday::[app]>Hello World
A pattern like dddd h:mm:ss a
would translate to something like "Sunday 12:55:07 am". You can easily switch to a 24h format as well, using these patterns.
- For all options, see moment.js
If you have included sprintf.js in your webapp, you can start using patterns with angular-logger.
Traditional style with $log
:
$log.error ("Error uploading document [" + filename + "], Error: '" + err.message + "'. Try again later.")
// Error uploading document [contract.pdf], Error: 'Service currently down'. Try again later. "{ ... }"
Modern style with angular-logger enhanced $log
:
var logger = $log.getInstance("myapp.file-upload");
logger.error("Error uploading document [%s], Error: '%s'. Try again later.", filename, err.message)
// Sunday 12:13:06 pm::[myapp.file-upload]> Error uploading document [contract.pdf], Error: 'Service currently down'. Try again later.
You can even combine pattern input and normal input:
var logger = $log.getInstance('test');
logger.warn("This %s pattern %j", "is", "{ 'in': 'put' }", "but this is not!", ['this', 'is', ['handled'], 'by the browser'], { 'including': 'syntax highlighting', 'and': 'console interaction' });
// 17-5-2015 00:16:08::[test]> This is pattern "{ 'in': 'put' }" but this is not! ["this", "is handled", "by the browser"] Object {including: "syntax highlighting", and: "console interaction"}
To log an Object
, you now have three ways of doing it, but the combined solution shown above has best integration with the browser.
logger.warn("Do it yourself: " + JSON.stringify(obj)); // json string with stringify's limitations
logger.warn("Let sprintf handle it: %j", obj); // json string with sprintf's limitations
logger.warn("Let the browser handle it: ", obj); // interactive tree in the browser with syntax highlighting
logger.warn("Or combine all!: %s, %j", JSON.stringify(obj), obj, obj);
- For all options, see sprintf.js
Using logging levels, we can manage output on several levels. Contexts can be named using dot '.' notation, where the names before dots are intepreted as groups or packages.
For example for a.b
and a.c
we can define a general log level for a
and have a different log level for only a.c
.
The following logging functions (left side) are available:
logging function | mapped to: | with logLevel
----------------- | --------------- | --------------
logger.trace
| $log.debug
| TRACE
logger.debug
| $log.debug
| DEBUG
logger.log*
| $log.log
| INFO
logger.info
| $log.info
| INFO
logger.warn
| $log.warn
| WARN
logger.error
| $log.error
| ERROR
*
maintained for backwards compatibility with $log.log
The level's order are as follows:
1. TRACE: displays all levels, is the finest output and only recommended during debugging
2. DEBUG: display all but the finest logs, only recommended during develop stages
3. INFO : Show info, warn and error messages
4. WARN : Show warn and error messages
5. ERROR: Show only error messages.
6. OFF : Disable all logging, recommended for silencing noisy logging during debugging. *will* surpress errors logging.
Example:
// config log levels before the application wakes up
app.config(function (logEnhancerProvider) {
logEnhancerProvider.prefixPattern = '%s::[%s]> ';
logEnhancerProvider.logLevels = {
'a.b.c': logEnhancerProvider.LEVEL.TRACE, // trace + debug + info + warn + error
'a.b.d': logEnhancerProvider.LEVEL.ERROR, // error
'a.b': logEnhancerProvider.LEVEL.DEBUG, // debug + info + warn + error
'a': logEnhancerProvider.LEVEL.WARN, // warn + error
'*': logEnhancerProvider.LEVEL.INFO // info + warn + error
};
// globally only INFO and more important are logged
// for group 'a' default is WARN and ERROR
// a.b.c and a.b.d override logging everything-with-TRACE and least-with-ERROR respectively
});
// modify log levels after the application started running
run(function ($log) {
$log.logLevels['a.b.c'] = $log.LEVEL.ERROR;
$log.logLevels['*'] = $log.LEVEL.OFF;
});