Class WL.Logger

WL.Logger

Description:

Module that wraps various loggers in order to provide a unified interface for logging that works in every environment.

In most environments, console.debug, console.log, console.info, console.warn and console.error are wrapped. The Android environment uses a cordova plugin that calls the native Android logger, log messages are shown in logcat with the appropriate colors. In Xcode, output is shown in the Xcode console.

Provides various features such as:

  • Package names.
  • Filtering by log level, package names using black or white lists.
  • Log instances.
  • Multiple argument support.
  • Callback for doing work after a log message has been sent to the console.
  • And others.
Example:
//The logger can be configured inside initOption.js, but doing so is discouraged.  An example configuration:
// ...
//logger : {enabled: true, level: 'debug', stringify: true, pretty: false,
//      tag: {level: false, pkg: true}},
// ...

//Make sure the MyNamespace variable exists.
var MyNamespace = MyNamespace || {};

//Define a module using the Module Pattern
MyNamespace.MyModule = (function () {

  //Create a logger "instance" specific to this module.
  //This is the recommended approach for logging.
  var logger = WL.Logger.create({pkg: 'mynamespace.mymodule'});

  //Example usage:
  logger.trace('trace', 'another mesage');
	 logger.debug('debug', [1,2,3], {hello: 'world'});
  logger.log('log', 'another message');
  logger.info('info', 1, 2, 3);
  logger.warn('warn', undefined);
  logger.error('error', new Error('oh no'));
  logger.fatal('fatal', 'another message');


}());

//Alternatively, you can use the "static" version.
//You probably want to use variables instead of duplicating
//the package name and other good programming practices.
//This is the recommended approach if you don't have modules.
WL.Logger.ctx({pkg: 'wl.whatever'}).trace('trace', 'another message');
WL.Logger.ctx({pkg: 'wl.whatever'}).debug('debug', [1,2,3], {hello: 'world'});
WL.Logger.ctx({pkg: 'wl.whatever'}).log('log', 'another message');
WL.Logger.ctx({pkg: 'wl.whatever'}).info('info', 1, 2, 3);
WL.Logger.ctx({pkg: 'wl.whatever'}).warn('warn', undefined);
WL.Logger.ctx({pkg: 'wl.whatever'}).error('error', new Error('oh no'));
WL.Logger.ctx({pkg: 'wl.whatever'}).fatal('fatal', 'another message');

//Alternatively, you do not have to pass a context.
//This is the least recommended approach.
WL.Logger.trace('trace', 'another message');
WL.Logger.debug('debug', [1,2,3], {hello: 'world'});
WL.Logger.log('log', 'another message');
WL.Logger.info('info', 1, 2, 3);
WL.Logger.warn('warn', undefined);
WL.Logger.error('error', new Error('oh no'));
WL.Logger.fatal('fatal', 'another message');

Method Summary
Method Attributes Method Name and Description
 
config(options)
Configures the logger globally.
 
create(options)
Creates an instance of a logger with its own context (also called status or state).
 
ctx(options)
Updates the state (also called context or status) of the logger.
 
debug(message)
Prints arguments to the console.
 
error(message)
Prints arguments to the console.
 
fatal(message)
Prints arguments to the console.
 
info(message)
Prints arguments to the console.
 
log(message)
Prints arguments to the console.
 
metadata(options)
Attach additional metadata to the next logger instance call.
 
off()
 
on(options)
 
send()
Send any logs collected up to this point to the IBM Worklight server.
 
setNativeOptions(options)
 
status()
Shows the status (current configuration) of the logger.
 
trace(message)
Prints arguments to the console.
 
Retrieves and applies any matching configuration profile from the IBM Worklight Server.
 
warn(message)
Prints arguments to the console.
Method Detail
config
{this} config(options)
Configures the logger globally. This means every logger instance created using WL.Logger.create, all uses of the global WL.Logger functions and any native API calls to the MobileFirst logger API are affected.
Parameters:
{object} options Optional - Defines the logger's behavior.
{boolean} options.stringify Optional - Turns arguments to strings and concatenates them (true) or leaves arguments as an array (false). Default is true.
{boolean} options.pretty Optional - Turn JSON into a human readable format. Default is false.
{boolean} options.stacktrace Optional - Enable/disable printing the stacktrace from an error message. Default is false.
{function} options.callback Optional - Called after a log message is sent to the console with the following parameters:
  • message (string or array) The log message. String if stringify is true, array otherwise.
  • level (string) Log level.
  • package (string) Package that is associated with the log or empty string.
{string} options.pkg Optional - Associates log messages with a package. By default does not associate (includes an empty string).
{object} options.tag Optional - Contains keys: level and tag.
{boolean} options.tag.level Optional - Appends log level tag to the string log message (true) or does nothing (false). Default is false.
{boolean} options.tag.pkg Optional - Appends package name string message (true) or does nothing (false). Default is false.
{string[]} options.whitelist Optional - List of packages from which to log messages. By default logs all messages (empty array). DEPRECATED since V6.2; use filters instead.
{string[]} options.blacklist Optional - List of packages to ignore log messages from. By default does not ignore any packages (empty array). DEPRECATED since V6.2; use filters instead.
{object} options.filters Optional - Object with key/value pairs like {'package': 'LEVEL'} for packages to log. This is treated as a whitelist; only log calls for instances matching pkg will be logged. Default is to log all messages (empty object). Explicitly pass an empty object or null (not undefined) to remove filters.
{boolean} options.capture Optional - Turn log capture on or off. This is meaningful in hybrid environments only.
{integer} options.maxFileSize Optional - Maximum amount of data (in bytes) to store in the file when capture is on. This is meaningful in hybrid environments only. Default is true.
{boolean} options.autoSendLogs Optional - Turn Auto Send Logs on or off. Auto logging occurs after each successful resource request, if no logging has occurred for 60 seconds.
{boolean} options.showLogsInConsole Optional - Turns displaying of logs in console on or off. This is meaningful in hybrid environments only
{string[]|string|number} options.level Optional - A list of one or more of the following items:
  • An array of the log levels to show. In JavaScript, only log calls at the listed levels are shown. In native code in a hybrid app, log output at and above the most verbose of the levels listed in the array are shown.
  • The name of the log level at which to set the logger. Output will be printed for log API calls at and above the configured level.
  • The Numeric Priority Level at which to set the logger. Output will be printed for log API calls at and above the configured level.
Default: Show all logs at all levels (empty array).
Returns:
{this} Returns the current instance.
Example:
WL.Logger.config()

Merge the passed object parameter with the current configuration, which can be retrieved using WL.Logger.status()

create
{LogInstance} create(options)
Creates an instance of a logger with its own context (also called status or state).
Parameters:
{Object} options Optional - See arguments defined for WL.Logger.config for information about the object that can be passed.
Returns:
{LogInstance} Has the following methods from WL.Logger: .trace, .debug, .log, .info, .warn, .error, and .fatal.
Example:
var logger = WL.Logger.create({pkg: 'mypackage'});

logger.trace('Hello world');
//[mypackage] Hello world

logger.debug('Hello world');
//[mypackage] Hello world

logger.log('Hello world');
//[mypackage] Hello world

logger.info('Hello world');
//[mypackage] Hello world

logger.warn('Hello world');
//[mypackage] Hello world

logger.error('Hello world');
//[mypackage] Hello world

logger.fatal('Hello world');
//[mypackage] Hello world

ctx
{this} ctx(options)
Updates the state (also called context or status) of the logger.
Parameters:
{object} options Optional - See arguments defined for WL.Logger.config for information about the object that can be passed.
Returns:
{this} Returns the current instance.
Example:
WL.Logger.debug('Hello world'); //No context passed
//Hello world

WL.Logger.ctx({pkg: 'hello'}).debug('Hello world'); //Package name context passed
//[hello] Hello world

Caution: filters, maxFileSize, capture, and level returned from this call may not accurately reflect the current behavior
   in hybrid applications if the native codebase has modified these settings in the native application layer.

debug
debug(message)
Prints arguments to the console. Has a priority of 500 and a level of DEBUG.
Parameters:
message - One or more messages of any data type.
Example:
WL.Logger.debug('Hello world');
//Hello world

error
error(message)
Prints arguments to the console. Has a priority of 100 and a level of ERROR.
Parameters:
message - One or more messages of any data type.
Example:
WL.Logger.error('Hello world');
//Hello world

fatal
fatal(message)
Prints arguments to the console. Has a priority of 50 and a level of FATAL.
Parameters:
message - One or more messages of any data type.
Example:
WL.Logger.fatal('Hello world');
//Hello world

info
info(message)
Prints arguments to the console. Has a priority of 300 and a level of INFO.
Parameters:
message - One or more messages of any data type.
Example:
WL.Logger.info('Hello world');
//Hello world

log
log(message)
Prints arguments to the console. Has a priority of 400 and a level of LOG.
Parameters:
message - One or more messages of any data type.
Example:
WL.Logger.log('Hello world');
//Hello world

metadata
metadata(options)
Attach additional metadata to the next logger instance call.
Parameters:
{Object} options Optional - an object to attach to the next logger instance call
Example:
WL.Logger.metadata(
    {
        userRealName : 'Robert Paulson'
    }
);
WL.Logger.metadata( { hi : 'world' } ).info('hello');

off
{this} off()
Returns:
{this} Returns the current instance.
Deprecated:
since version 6.2. WL.Logger.off is now a NOP. WL.Logger is always enabled. Use WL.Logger.config with {'level': 'FATAL'} to reduce verbosity.

on
{this} on(options)
Parameters:
options
Returns:
{this} Returns the current instance.
Deprecated:
since version 6.2. WL.Logger.on is now a no-op. WL.Logger is always enabled. Use WL.Logger.config with {'level': 'FATAL'} to reduce verbosity.

send
{Promise} send()
Send any logs collected up to this point to the IBM Worklight server.
Returns:
{Promise} Resolved with success status, rejected with an error message.

setNativeOptions
setNativeOptions(options)
Parameters:
{Object} options Optional - an object that optionally contains any of the following key/value pairs:
  • maxFileSize: integer (minimum allowed is 10000 (in bytes))
  • level: String (any of the following values: 'trace', debug', 'log', 'info', 'warn', 'error', 'fatal')
  • capture: boolean
Deprecated:
since version 6.2. Use WL.Logger.config instead. Sets options in native application layer (iOS and Android only)
Example:
WL.Logger.setNativeOptions(
    {
        maxFileSize : 100000,              // allow persistent storage of up to 100k of log data
        level : 'debug',                   // at debug (and above) level
        capture : true,                    // capture data passed to log API calls into persistent storage
        filters : { jsonstore : 'debug' }  // establish whitelist filters at native
    }
);

status
{Promise} status()
Shows the status (current configuration) of the logger.
Returns:
{Promise} Resolved with current status, rejected with an error message.
Example:
WL.Logger.status()

.then(function (state) {
//{ enabled : true, stringify: true, filters : {},
// level : 'info', pkg : '', tag: {level: false, pkg: true} }
})

.fail(function (errMsg) {
  //errMsg = error message
});

trace
trace(message)
Prints arguments to the console. Has a priority of 600 and a level of TRACE.
Parameters:
message - One or more messages of any data type.
Example:
WL.Logger.trace('Hello world');
//Hello world

updateConfigFromServer
updateConfigFromServer()
Retrieves and applies any matching configuration profile from the IBM Worklight Server. A matching configuration profile acts as an override of the local configuration. Configuration profiles are defined by the IBM Worklight administrator in the Worklight admin console. Restores to original settings when the server indicates that no matching configuration profile exists. This API call is only applicable in Android and IOS environments. It is a safe, but no-op, call in other environments.
Returns:
promise

warn
warn(message)
Prints arguments to the console. Has a priority of 200 and a level of WARN.
Parameters:
message - One or more messages of any data type.
Example:
WL.Logger.warn('Hello world');
//Hello world

© Copyright IBM Corp. 2011, 2016.