log4javascript 1.3 manual

Contents

A note about the distribution

As from 1.3, the log4javascript distribution includes four main JavaScript files:

  • log4javascript.js

    This is the main file for general use. Unlike in previous versions, this file is compressed (i.e. whitespace and comments have been removed) but is functionally identical to the uncompressed version.

  • log4javascript_uncompressed.js

    The uncompressed version of the main file with all comments and indentation included.

  • log4javascript_stub.js

    Contains stub implementations of all log4javacript objects and methods in the public API, making it ideal for production environments where logging is not required. Replacing the log4javascript.js file with this file means that log calls may be left in production code.

  • log4javascript_stub_uncompressed.js

    An uncompressed version of log4javascript_stub.js file, functionally identical to the compressed version.

Top

Introduction

Anyone who has done a reasonable amount of JavaScript development will be familiar with alert as a means of debugging. For a small script, it works fine. But for anything of greater complexity than, say, a rollover script its shortcomings become apparent. The most obvious problem is the endless clicking of 'OK'. Another problem is that for a page heavily reliant on events generated from user actions, alerts can actually alter the way the page behaves. One final problem is infinite loops: without alerts, the browser will notice that the script has messed up and will offer the user the chance to stop the script running. With an alert inside an infinite loop, you're forced to kill the browser.

At the other end of the scale there is Venkman, a full-on JavaScript debugger for Mozilla-based browsers such as Firefox. Here I have to confess that I simply have not put in the time to learn how to make it work well for me, and I suspect I am not alone.

log4javascript was written as a tool to ease the pain of JavaScript debugging without the time investment required to use a debugger effectively. It requires only a JavaScript include and one line of code to initialize with default settings. It was natural to base it on log4j, since I am a Java programmer and have used and liked log4j and its C# implementation log4net for several years.

log4javascript is by no means the only JavaScript logging framework out there. It is not even the only JavaScript implementation of log4j, although many of the others have sprung up in the last year or so, during which time I had a half-written version of log4javascript that I had intended to call log4js but never got round to completing. I have recently discovered that the name log4javascript is used by another JavaScript logging framework, and that the name log4js is now used by at least two other pieces of software; this version of log4javascript is unrelated to any of those.

Top

Note about the log4javascript object

All of log4javascript's instantiable classes are accessible via the log4javascript object, which acts as a namespace. Therefore references to all class names must be preceded with "log4javascript.". For example:

var popUpAppender = new log4javascript.PopUpAppender();

Top

Loggers, Appenders, Layouts and Levels

A logger in log4javascript is the object on which log calls are made. A logger may be assigned zero or more appenders. An appender is an object that actually does the logging: for example, a PopUpAppender logs messages to a pop-up console window while an AjaxAppender uses HTTP to send log messages back to the server. Each appender is assigned a layout, which is responsible for formatting log messages that are passed to an appender.

Every log message has a level. This is the severity of the message. Available levels are TRACE, DEBUG, INFO, WARN, ERROR and FATAL - these correspond to the logging methods trace, debug, info, warn, error and fatal of Logger. Levels are ordered as follows: TRACE < DEBUG < INFO < WARN < ERROR < FATAL. This means the FATAL is the most severe and TRACE the least. Also included are levels called ALL and OFF intended to enable or disable all logging respectively.

Both loggers and appenders also have threshold levels (by default, DEBUG for loggers and ALL for appenders). Setting a level to either a logger or an appender disables log messages of severity lower than that level. For instance, if a level of INFO is set on a logger then only log messages of severity INFO or greater will be logged, meaning DEBUG and TRACE messages will not be logged. If the same logger had two appenders, one of level DEBUG and one of level WARN then the first appender will still only log messages of INFO or greater while the second appender will only log messages of level WARN or greater.

This allows the developer fine control over which messages get logged where.

Configuring appenders

As of log4javascript 1.1, there are two principal ways to configure appenders:

  • Constructor parameters

    For example:

    var p = new log4javascript.PopUpAppender(null, true, true, true, true, false, true, false, 600, 400);

    This has the advantage of being fairly concise and gets all the configuration out of the way in one fell swoop, but has two big disadvantages: firstly, it's not very readable as you either have to remember a fairly long list of constructor parameters or refer to the documentation. Secondly, if the default configuration values are fine for your purposes except for one, you still have to enter all the other parameters in the constructor. To ease the pain slightly, log4javascript interprets null parameters in appender constructors to mean "use the default".

  • Setters

    For example:

    var p = new log4javascript.PopUpAppender(); p.setFocusPopUp(true);

    This is much more readable and reduces the need to refer to documentation, but has the disadvantage of being rather verbose if more than one or two configuration properties differ from the default. In general, however, this is probably the better way to configure appenders.

    Most configuration setters may only be used before a message is logged. It's therefore easiest to put your configuration code immediately after the instantiation code. Refer to the individual appender documentation for full details of which properties may be set when.

Example

NB. The Ajax side of this example relies on having server-side processing in place.

First, log4javascript is initialized, and a logger with name "main" is created and assigned to a variable called log:

<script type="text/javascript" src="log4javascript.js"></script>
<script type="text/javascript">
	//<![CDATA[
	var log = log4javascript.getLogger("main");

log does not yet have any appenders, so a call to log.debug() will do nothing as yet. For this example we will use a PopUpAppender for debugging purposes. Since the lifespan of the messages displayed in the pop-up is only going to be the same as that of the window, a PatternLayout is used that displays the time of the message and not the date (note that this is also true of PopUpAppender's default layout). The format of the string passed into PatternLayout is explained below.

	var popUpAppender = new log4javascript.PopUpAppender();
	var popUpLayout = new log4javascript.PatternLayout("%d{HH:mm:ss} %-5p - %m%n");
	popUpAppender.setLayout(popUpLayout);
	log.addAppender(popUpAppender);

Suppose that we also want to send log messages to the server, but limited to error messages only. To achieve this we use an AjaxAppender. Note that if no layout is specified then for convenience a default layout is used; in the case of AjaxAppender, that is HttpPostDataLayout, which formats log messages as a standard HTTP POST string from which a simple server-side script (not provided with log4javascript) will be able to extract posted parameters. This is fine for our purposes:

	var ajaxAppender = new log4javascript.AjaxAppender("myloggingservlet.do");
	ajaxAppender.setThreshold(log4javascript.Level.ERROR);
	log.addAppender(ajaxAppender);

Finally, some test log messages and the closing script tag:

	log.debug("Debugging message (appears in pop-up)");
	log.error("Error message (appears in pop-up and in server log)");
	//]]>
</script>

The full script:

<script type="text/javascript" src="log4javascript.js"></script>
<script type="text/javascript">
	//<![CDATA[
	var log = log4javascript.getLogger("main");
	var popUpAppender = new log4javascript.PopUpAppender();
	var popUpLayout = new log4javascript.PatternLayout("%d{HH:mm:ss} %-5p - %m%n");
	popUpAppender.setLayout(popUpLayout);
	log.addAppender(popUpAppender);
	var ajaxAppender = new log4javascript.AjaxAppender("myloggingservlet.do");
	ajaxAppender.setThreshold(log4javascript.Level.ERROR);
	log.addAppender(ajaxAppender);
	log.debug("Debugging message (appears in pop-up)");
	log.error("Error message (appears in pop-up and in server log)");
	//]]>
</script>

See this example in action (opens in new window)

Top

log4javascript static properties/methods

Properties

  • version
    The version number of your copy of log4javascript.
  • logLog
    log4javascript's internal logging object. See below for more details.

Methods

  • getLogger
    Logger getLogger(String loggerName)
    Parameters:
    • loggerName [optional]

    Returns a logger with the specified name, creating it if a logger with that name does not already exist. If no name is specified, a logger is returned with name "[anonymous]", and subsequent calls to getLogger() (with no logger name specified) will return this same logger object.

    Note that the names "[anonymous]", "[default]" and "[null]" are reserved for the anonymous logger, default logger and null logger respectively.

  • getDefaultLogger
    Logger getDefaultLogger()
    Convenience method that returns the default logger. The default logger has a single appender: a PopUpAppender with the default layout, width and height, and with focusPopUp set to false and lazyInit, keepLogWhenPageReloads and complainAboutPopUpBlocking all set to true.
  • getNullLogger
    Logger getNullLogger()
    Returns an empty logger with no appenders. Useful for disabling all logging.
  • setEnabled
    void setEnabled(Boolean enabled)
    Parameters:
    • enabled
    Enables or disables all logging, depending on enabled.
  • isEnabled
    Boolean isEnabled()
    Returns true or false depending on whether logging is enabled.
  • addErrorListener
    void addErrorListener(Function listener)
    Parameters:
    • listener
    Add a function to be called when an error occurs in log4javascript. Each listener is passed one or two parameters: message is always passed and is the error-specific message, and exception, which is the original Error object, if one exists.
  • removeErrorListener
    void removeErrorListener(Function listener)
    Parameters:
    • listener
    Removes a function from the list of functions called when an error occurs in log4javascript.
  • setShowStackTraces
    void setShowStackTraces(Boolean show)
    Parameters:
    • show
    Enables or disables displaying of error stack traces, depending on show. By default, stack traces are not displayed. (Only works in Firefox)
  • evalInScope
    Object evalInScope(String expr)
    Parameters:
    • expr
    This evaluates the given expression in the log4javascript scope, thus allowing scripts to access private variables and functions. This is intended for automated testing but could be used by custom extensions to log4javascript.

Top

Loggers

It is possible to have multiple loggers in log4javascript. For example, you may wish to have a logger for debugging purposes that logs messages to a pop-up window and a separate logger that reports any client-side application errors to the server via Ajax.

Unlike log4j, there is no hierarchy of loggers in log4javascript. Each logger simply has a unique name and exists independently from all other loggers. Hence each logger must be configured from scratch.

Notes

  • It is not possible to instantiate loggers directly. Instead you must use one of the methods of the log4javascript object: getLogger, getDefaultLogger or getNullLogger.

Logger methods

  • addAppender
    void addAppender(Appender appender)
    Parameters:
    • appender
    Adds the given appender appender.
  • removeAppender
    void removeAppender(Appender appender)
    Parameters:
    • appender
    Removes the given appender.
  • removeAllAppenders
    void removeAllAppenders()
    Clears all appenders for the current logger.
  • setLevel
    void setLevel(Level level)
    Parameters:
    • level
    Sets the level. Log messages of a lower level than level will not be logged. Default value is DEBUG.
  • getLevel
    Level getLevel()
    Returns the current level.
  • log
    void log(Level level, String message, Error exception)
    Parameters:
    • level
    • message
    • exception [optional]
    Generic logging method. Logs a message and optionally an error at level level.
  • trace
    void trace(String message, Error exception)
    Parameters:
    • message
    • exception [optional]
    Logs a message and optionally an error at level TRACE.
  • debug
    void debug(String message, Error exception)
    Parameters:
    • message
    • exception [optional]
    Logs a message and optionally an error at level DEBUG.
  • info
    void info(String message, Error exception)
    Parameters:
    • message
    • exception [optional]
    Logs a message and optionally an error at level INFO.
  • warn
    void warn(String message, Error exception)
    Parameters:
    • message
    • exception [optional]
    Logs a message and optionally an error at level WARN.
  • error
    void error(String message, Error exception)
    Parameters:
    • message
    • exception [optional]
    Logs a message and optionally an error at level ERROR.
  • fatal
    void fatal(String message, Error exception)
    Parameters:
    • message
    • exception [optional]
    Logs a message and optionally an error at level FATAL.

Top

Appenders

Appender

There are methods common to all appenders, as listed below.

Methods

  • doAppend
    void doAppend(LoggingEvent loggingEvent)
    Parameters:
    • loggingEvent

    Checks the logging event's level is at least as severe as the appender's threshold and calls the appender's append method if so.

    This method should not in general be used directly or overridden.

  • append
    void append(LoggingEvent loggingEvent)
    Parameters:
    • loggingEvent
    Appender-specific method to append a log message. Subclasses should implement this method.
  • setLayout
    void setLayout(Layout layout)
    Parameters:
    • layout
    Sets the appender's layout.
  • getLayout
    Layout getLayout()
    Returns the appender's layout.
  • setThreshold
    void setThreshold(Level level)
    Parameters:
    • level
    Sets the appender's threshold. Log messages of level less severe than this threshold will not be logged.
  • getThreshold
    Level getThreshold()
    Returns the appender's threshold.
  • toString
    string toString()
    Returns a string representation of the appender.

Top

AlertAppender

Displays a log message as a JavaScript alert.

Constructor

  • AlertAppender
    AlertAppender(Layout layout)
    Parameters:
    • layout [optional]
      The layout for the appender. If not specified, defaults to SimpleLayout.

Top

AjaxAppender

A flexible appender that asynchronously sends log messages to a server via HTTP (Ajax, if you insist, though the 'x' of Ajax only comes into play in any form if you use an XmlLayout).

The default configuration is to send each log message as a separate HTTP post request to the server using an HttpPostDataLayout, without waiting for a response before sending any subsequent requests. However, an AjaxAppender may be configured to do any one of or combinations of the following:

  • send log messages in batches (if the selected layout supports it - particularly suited to AjaxAppender are JsonLayout and XmlLayout, both of which allow batching);
  • wait for a response from a previous request before sending the next log message / batch of messages;
  • send all queued log messages at timed intervals.

Notes

  • AjaxAppender relies on the XMLHttpRequest object. It also requires the presence of correctly implemented setRequestHeader method on this object, which rules out Opera prior to version 8.01. If your browser does not support the necessary objects then one alert will display to explain why it doesn't work, after which the appender will silently switch off.
  • In AjaxAppender only, setLayout may not be called after the first message has been logged.

Constructor

  • AjaxAppender
    AjaxAppender(String url, Layout layout, Boolean timed, Boolean waitForResponse, Number batchSize, Number timerInterval, Function requestSuccessCallback, Function failCallback)
    Parameters:
    • url
      The URL to which log messages should be sent. Note that this is subject to the usual Ajax restrictions: the URL should be in the same domain as that of the page making the request.
    • layout [optional]
      The layout for the appender. If not specified, defaults to HttpPostDataLayout.
    • timed [optional]
      Whether to send log messages to the server at regular, timed intervals. If not specified, defaults to false.
    • waitForResponse [optional]
      Whether to wait for a response from a previous HTTP request from this appender before sending the next log message / batch of messages. If not specified, defaults to false.
    • batchSize [optional]

      The number of log messages to send in each request. If not specified, defaults to 1.

      Notes

      • Setting this to a number greater than 1 means that the appender will wait until it has forwarded that many valid log messages before sending any. This also means that if the page unloads for any reason, any log messages waiting in the queue will not be sent.
      • If batching is used in conjunction with timed sending of log messages, messages will still be sent in batches of size batchSize, regardless of how many log messages are queued by the time the timed sending is invoked. Incomplete batches will not be sent.
    • timerInterval [optional]

      The length of time in milliseconds between each sending of queued log messages.

      Notes

      • timerInterval only has an effect in conjunction with timed. If timed is set to false then timerInterval has no effect.
      • Each time the queue of log messages or batches of messages is cleared, the countdown to the next sending only starts once the final request has been sent (and, if waitForResponse is set to true, the final response received). This means that the actual interval at which the queue of messages is cleared cannot be fixed.
    • requestSuccessCallback [optional]

      A function that is called whenever a successful request is made, called at the point at which the response is received. This feature can be used to confirm whether a request has been successful and act accordingly.

      A single parameter, xmlHttp, is passed to the callback function. This is the XMLHttpRequest object that performed the request.

    • failCallback [optional]

      A function that is called whenever any kind of failure occurs in the appender, including browser deficiencies or configuration errors (e.g. supplying a non-existent URL to the appender). This feature can be used to handle AjaxAppender-specific errors.

      A single parameter, message, is passed to the callback function. This is the error-specific message that caused the failure.

Methods

  • isTimed
    Boolean isTimed()
    Returns whether log messages are sent to the server at regular, timed intervals.
  • setTimed
    void setTimed(Boolean timed)
    [not available after first message logged]
    Sets whether to send log messages to the server at regular, timed intervals.
  • isWaitForResponse
    Boolean isWaitForResponse()
    Returns whether the appender waits for a response from a previous HTTP request from this appender before sending the next log message / batch of messages.
  • setWaitForResponse
    void setWaitForResponse(Boolean waitForResponse)
    [not available after first message logged]
    Sets whether to wait for a response from a previous HTTP request from this appender before sending the next log message / batch of messages.
  • getBatchSize
    Number getBatchSize()
    Returns the number of log messages sent in each request. See constructor for more details.
  • setBatchSize
    void setBatchSize(Number batchSize)
    [not available after first message logged]
    Sets the number of log messages to send in each request. See constructor for more details.
  • getTimerInterval
    Number getTimerInterval()
    Returns the length of time in milliseconds between each sending of queued log messages. See constructor for more details.
  • setTimerInterval
    void setTimerInterval(Number timerInterval)
    [not available after first message logged]
    Sets the length of time in milliseconds between each sending of queued log messages. See constructor for more details.
  • setRequestSuccessCallback
    void setRequestSuccessCallback(Function requestSuccessCallback)
    Sets the function that is called whenever a successful request is made. See constructor for more details.
  • setFailCallback
    void setFailCallback(Function failCallback)
    Sets the function that is called whenever any kind of failure occurs in the appender. See constructor for more details.
  • getSessionId
    String getSessionId()
    Returns the session id sent to the server each time a request is made.
  • setSessionId
    void setSessionId(String sessionId)

    Sets the session id sent to the server each time a request is made.
  • sendAll
    void sendAll()
    Sends all log messages in the queue. If log messages are batched then only completed batches are sent.

Top

PopUpAppender

Logs messages to a pop-up console window (note: you will need to disable pop-up blockers to use it). The pop-up displays a list of all log messages, and has the following features:

  • log messages are colour-coded by severity;
  • log messages are displayed in a monospace font to allow easy readability;
  • switchable Wrap mode to allow wrapping of long lines
  • all whitespace in log messages is honoured (except in Wrap mode);
  • filters to show and hide messages of a particular level;
  • search facility that allows searching of log messages as you type, with the following features:
    • supports regular expressions;
    • case sensitive or insensitive matching;
    • buttons to navigate through all the matches;
    • switch to highlight all matches;
    • switch to filter out all log messages that contain no matches;
    • switch to enable or disable the search;
    • search is dynamically applied to every log message as it is added to the console.
  • switch to toggle between logging from the top down and from the bottom up;
  • switch to turn automatic scrolling when a new message is logged on and off;
  • switch to turn off all logging to the pop-up (useful if a timer is generating unnecessary log messages);
  • optional configurable limit to the number of log message that are displayed. If set and this limit is reached, each new log message will cause the oldest one to be discarded;
  • clear button to allow user to delete all current log messages.

Constructor

  • PopUpAppender
    PopUpAppender(Boolean lazyInit, Layout layout, Boolean focusPopUp, Boolean useOldPopUp, Boolean complainAboutPopUpBlocking, Boolean newestMessageAtTop, Boolean scrollToLatestMessage, Boolean reopenWhenClosed, Number width, Number height, Number maxMessages)
    Parameters:
    • lazyInit [optional]
      Set this to true to open the pop-up only when the first log message reaches the appender. Otherwise, the pop-up window opens as soon as the appender is created. If not specified, defaults to false.
    • layout [optional]

      The layout for the appender. If not specified, defaults to PatternLayout with pattern string

      %d{HH:mm:ss} %-5p - %m{1}%n

      Notes

      • Prior to version 1.3, the layout and lazyInit parameters were specified the other way round. This has been changed so that in common with all other appenders, parameters that can only be specified in the constructor (in this case lazyInit) are specifed first.
    • focusPopUp [optional]
      Whether to focus the pop-up window (i.e. bring it to the front) when a new log message is added. If not specified, defaults to false.
    • useOldPopUp [optional]

      Whether to use the same pop-up window if the main page is reloaded. If set to true, when the page is reloaded a line is drawn in the pop-up and subsequent log messages are added to the same pop-up. Otherwise, a new pop-up window is created that replaces the original pop-up. If not specified, defaults to true.

      Notes

      • In Internet Explorer 5, the browser prevents this from working properly, so a new pop-up window is always created when the main page reloads. Also, the original pop-up does not get closed.
    • complainAboutPopUpBlocking [optional]
      Whether to announce to show an alert to the user when the pop-up window cannot be created as a result of a pop-up blocker. If not specified, defaults to true.
    • newestMessageAtTop [optional]
      Whether to display new log messages at the top inside the pop-up window. If not specified, defaults to false (i.e. log messages are appended to the bottom of the window).
    • scrollToLatestMessage [optional]
      Whether to scroll the pop-up window to display the latest message. If not specified, defaults to true
    • reopenWhenClosed [optional]
      Whether to reopen the pop-up window automatically at the time of the next log entry after the original window was closed. If not specified, defaults to false
    • width [optional]
      The outer width in pixels of the pop-up window. If not specified, defaults to 600.
    • height [optional]
      The outer height in pixels of the pop-up window. If not specified, defaults to 400.
    • maxMessages [optional]
      The largest number of log messages that are displayed and stored by the the console. Once reached, a new log message wil cause the oldest message to be discarded. If not specified, defaults to null, which means no limit is applied.
  • isFocusPopUp
    Boolean isFocusPopUp()
    Returns whether the pop-up window is focussed (i.e. brought it to the front) when a new log message is added.
  • setFocusPopUp
    void setFocusPopUp(Boolean focusPopUp)
    Sets whether to focus the pop-up window (i.e. bring it to the front) when a new log message is added.
  • isUseOldPopUp
    Boolean isUseOldPopUp()
    Returns whether any existing pop-up window is to be used. See constructor for details.
  • setUseOldPopUp
    void setUseOldPopUp(Boolean useOldPopUp)
    [not available after initialization]
    Sets whether to use the same pop-up window if the main page is reloaded. See constructor for details.
  • isComplainAboutPopUpBlocking
    Boolean isComplainAboutPopUpBlocking()
    Returns whether an alert is shown to the user when the pop-up window cannot be created as a result of a pop-up blocker.
  • setComplainAboutPopUpBlocking
    void setComplainAboutPopUpBlocking(Boolean complainAboutPopUpBlocking)
    [not available after initialization]
    Sets whether to announce to show an alert to the user when the pop-up window cannot be created as a result of a pop-up blocker.
  • isNewestMessageAtTop
    Boolean isNewestMessageAtTop()
    Returns whether new log messages are displayed at the top of the pop-up window.
  • setNewestMessageAtTop
    void setNewestMessageAtTop(Boolean newestMessageAtTop)
    Sets whether to display new log messages at the top inside the pop-up window.
  • isScrollToLatestMessage
    Boolean isScrollToLatestMessage()
    Returns whether the pop-up window scrolls to display the latest log message when a new message is logged.
  • setScrollToLatestMessage
    void setScrollToLatestMessage(Boolean scrollToLatestMessage)
    Sets whether to scroll the pop-up window to display the latest log message when a new message is logged.
  • isReopenWhenClosed
    Boolean isReopenWhenClosed()
    Returns whether the pop-up window reopens automatically after being closed when a new log message is logged.
  • setReopenWhenClosed
    void setReopenWhenClosed(Boolean reopenWhenClosed)
    Sets whether to reopen the pop-up window automatically after being closed when a new log message is logged.
  • getWidth
    Number getWidth()
    Returns the outer width in pixels of the pop-up window.
  • setWidth
    void setWidth(Number width)
    [not available after initialization]
    Sets the outer width in pixels of the pop-up window.
  • getHeight
    Number getHeight()
    [not available after initialization]
    Returns the outer height in pixels of the pop-up window.
  • setHeight
    void setHeight(Number height)
    Sets the outer height in pixels of the pop-up window.
  • getMaxMessages
    Number getMaxMessages()
    Returns the largest number of messages displayed and stored by the console window.
  • setMaxMessages
    void setMaxMessages(Number mxMessages)
    [not available after initialization]
    Sets the largest number of messages displayed and stored by the console window. Set this to null to make this number unlimited.
  • close
    void close()
    Closes the pop-up window.

Top

InPageAppender

Logs messages to a console window in the page. The console is identical to that used by the PopUpAppender, except for the absence of a 'Close' button.

Notes

  • Prior to log4javascript 1.3, InPageAppender was known as InlineAppender. For the sake of backwards compatibility, InlineAppender is still included in 1.3 as an alias for InPageAppender.

Constructor

  • InPageAppender
    InPageAppender(HTMLElement containerElement, Boolean lazyInit, Layout layout, Boolean initiallyMinimized, Boolean newestMessageAtTop, Boolean scrollToLatestMessage, String width, String height, Number maxMessages)
    Parameters:
    • containerElement
      The container element for the console window. This should be an HTML element.
    • lazyInit [optional]
      Set this to true to create the console only when the first log message reaches the appender. Otherwise, the console is initialized as soon as the appender is created. If not specified, defaults to true.
    • layout [optional]

      The layout for the appender. If not specified, defaults to PatternLayout with pattern string

      %d{HH:mm:ss} %-5p - %m{1}%n

    • initiallyMinimized [optional]

      Whether the console window should start off hidden / minimized. If not specified, defaults to false.

      Notes

      • In Safari (and possibly other browsers) hiding an iframe resets its document, thus destroying the console window.
    • newestMessageAtTop [optional]
      Whether to display new log messages at the top inside the console window. If not specified, defaults to false (i.e. log messages are appended to the bottom of the window).
    • scrollToLatestMessage [optional]
      Whether to scroll the pop-up window to display the latest message. If not specified, defaults to true
    • width [optional]
      The width of the console window. Any valid CSS length may be used. If not specified, defaults to 100%.
    • height [optional]
      The height of the console window. Any valid CSS length may be used. If not specified, defaults to 250px.
    • maxMessages [optional]
      The largest number of log messages that are displayed and stored by the the console. Once reached, a new log message wil cause the oldest message to be discarded. If not specified, defaults to null, which means no limit is applied.

Methods

  • isInitiallyMinimized
    Boolean isInitiallyMinimized()
    Returns whether the console window starts off hidden / minimized.
  • setInitiallyMinimized
    void setInitiallyMinimized(Boolean initiallyMinimized)
    [not available after initialization]
    Sets whether the console window should start off hidden / minimized.
  • isNewestMessageAtTop
    Boolean isNewestMessageAtTop()
    Returns whether new log messages are displayed at the top of the console window.
  • setNewestMessageAtTop
    void setNewestMessageAtTop(Boolean newestMessageAtTop)
    Sets whether to display new log messages at the top inside the console window.
  • isScrollToLatestMessage
    Boolean isScrollToLatestMessage()
    Returns whether the pop-up window scrolls to display the latest log message when a new message is logged.
  • setScrollToLatestMessage
    void setScrollToLatestMessage(Boolean scrollToLatestMessage)
    Sets whether to scroll the console window to display the latest log message when a new message is logged.
  • getWidth
    String getWidth()
    Returns the outer width of the console window.
  • setWidth
    void setWidth(String width)
    [not available after initialization]
    Sets the outer width of the console window. Any valid CSS length may be used.
  • getHeight
    String getHeight()
    Returns the outer height of the console window.
  • setHeight
    void setHeight(String height)
    [not available after initialization]
    Sets the outer height of the console window. Any valid CSS length may be used.
  • getMaxMessages
    Number getMaxMessages()
    Returns the largest number of messages displayed and stored by the console window.
  • setMaxMessages
    void setMaxMessages(Number mxMessages)
    [not available after initialization]
    Sets the largest number of messages displayed and stored by the console window. Set this to null to make this number unlimited.
  • show
    void show()

    Shows / unhides the console window.

    Notes

    • In Safari (and possibly other browsers), hiding an iframe resets its document, thus destroying the console window.
  • hide
    void hide()

    Hides / minimizes the console window.

    Notes

    • In Safari (and possibly other browsers), hiding an iframe resets its document, thus destroying the console window.
  • close
    void close()
    Removes the console window iframe from the main document.

Top

BrowserConsoleAppender

Writes log messages to the browser's built-in console, if present. This only works currently in Safari, Opera and Firefox with the excellent FireBug extension installed.

Notes

  • As of log4javascript 1.3, the default threshold for this appender is DEBUG as opposed to WARN as it was previously;
  • As of version 1.3, log4javascript has explicit support for FireBug's logging. This includes the following mapping of log4javascript's log levels onto FireBug's:

    • log4javascript TRACE, DEBUG -> FireBug debug
    • log4javascript INFO -> FireBug info
    • log4javascript WARN -> FireBug warn
    • log4javascript ERROR, FATAL -> FireBug error

    ... and the ability to pass objects into FireBug and take advantage of its object inspection. This is because the default layout is now NullLayout, which performs no formatting on an object.

Constructor

  • BrowserConsoleAppender
    BrowserConsoleAppender(Layout layout)
    Parameters:
    • layout [optional]

      The layout for the appender. If not specified, defaults to NullLayout.

      Notes

      • Prior to log4javascript 1.3, the default layout was SimpleLayout

Top

Layouts

Layout

There are a few methods common to all layouts:

Methods

  • format
    String format(LoggingEvent loggingEvent)
    Parameters:
    • loggingEvent
    Formats the log message. You should override this method in your own layouts.
  • ignoresThrowable
    Boolean ignoresThrowable()
    Returns whether the layout ignores an error object in a logging event passed to its format method.
  • getContentType
    String getContentType()
    Returns the content type of the output of the layout.
  • allowBatching
    Boolean allowBatching()
    Returns whether the layout's output is suitable for batching. JsonLayout and XmlLayout are the only layouts that return true for this method.
  • getDataValues
    Array getDataValues(LoggingEvent loggingEvent)
    Parameters:
    • loggingEvent
    Used internally by log4javascript in constructing formatted output for some layouts.
  • setKeys
    void setKeys(String loggerKey, String timeStampKey, String levelKey, String messageKey, String exceptionKey, String urlKey)
    Parameters:
    • loggerKey
      Parameter to use for the log message's logger name. Default is logger.
    • timeStampKey
      Parameter to use for the log message's timestamp. Default is timestamp.
    • levelKey
      Parameter to use for the log message's level. Default is level.
    • messageKey
      Parameter to use for the message itself. Default is message.
    • exceptionKey
      Parameter to use for the log message's error (exception). Default is exception.
    • urlKey
      Parameter to use for the current page URL. Default is url.
    This method is used to change the default keys used to create formatted name-value pairs for the properties of a log message, for layouts that do this. These layouts are JsonLayout and HttpPostDataLayout.
  • setCustomField
    void setCustomField(String name, String value)
    Parameters:
    • name
      Name of the custom property you wish to be included in the formmtted output.
    • value
      Value of the custom property you wish to be included in the formatted output.
    Some layouts (JsonLayout, HttpPostDataLayout, PatternLayout and XmlLayout) allow you to set custom fields (e.g. a session id to send to the server) to the formatted output. Use this method to set a custom field. If there is already a custom field with the specified name, its value will be updated with value.
  • hasCustomFields
    Boolean hasCustomFields()
    Returns whether the layout has any custom fields.

Top

NullLayout

The most basic layout. NullLayout's format() methods performs no formatting at all and simply returns the message property of the logging event.

Constructor

  • NullLayout
    NullLayout()

Top

SimpleLayout

Provides the most basic formatting. SimpleLayout consists of the level of the log statement, followed by " - " and then the log message itself. For example,

DEBUG - Hello world

Constructor

  • SimpleLayout
    SimpleLayout()

Top

PatternLayout

Provides a flexible way of formatting a log message by means of a conversion pattern string. The behaviour of this layout is a full implementation of PatternLayout in log4j, with the exception of the set of conversion characters - log4javascript's is necessarily a subset of that of log4j with a few additions of its own, since many of the conversion characters in log4j only make sense in the context of Java.

The conversion pattern consists of literal text interspersed with special strings starting with a % symbol called conversion specifiers. A conversion specifier consists of the % symbol, a conversion character (possible characters are listed below) and format modifiers. For full documentation of the conversion pattern, see log4j's documentation. Below is a list of all conversion characters available in log4javascript.

Conversion characters

Conversion Character Effect
c

Outputs the logger name.

d

Outputs the date of the logging event. The date conversion specifier may be followed by a date format specifier enclosed between braces. For example, %d{HH:mm:ss,SSS} or %d{dd MMM yyyy HH:mm:ss,SSS}. If no date format specifier is given then ISO8601 format is assumed.

The date format specifier is the same as that used by Java's SimpleDateFormat. log4javascript includes a full implementation of SimpleDateFormat's format method, with the exception of the pattern letter 'z', (string representation of the timezone) for which the information is not available in JavaScript.

f

Outputs the value of a custom field set on the layout. If present, the specifier gives the index in the array of custom fields to use; otherwise, the first custom field in the array is used.

Since: 1.3

m

Outputs the message property of the logging event (i.e. the logging message supplied by the client code).

As of version 1.3, an object may be specified as the log message and will be expanded to show its properties in the output, provided that a specifier containing the number of levels to expand is provided. If no specifier is provided then the message will be treated as a string regardless of its type. For example, %m{1} will display an expansion of the object one level deep, i.e. each property of the object will be displayed but if the property value is itself an object it will not be expanded and will appear as [object Object].

n

Outputs a line separator.

p

Outputs the level of the logging event.

r

Outputs the number of milliseconds since log4javascript was initialized.

%

The sequence %% outputs a single percent sign.

Static properties

  • TTCC_CONVERSION_PATTERN
    Built-in conversion pattern, equivalent to %r %p %c - %m%n.
  • DEFAULT_CONVERSION_PATTERN
    Built-in conversion pattern, equivalent to %m%n.
  • ISO8601_DATEFORMAT
    Built-in date format (and also the default), equivalent to yyyy-MM-dd HH:mm:ss,SSS.
  • DATETIME_DATEFORMAT
    Built-in date format, equivalent to dd MMM YYYY HH:mm:ss,SSS.
  • ABSOLUTETIME_DATEFORMAT
    Built-in date format, equivalent to HH:mm:ss,SSS.

Constructor

  • PatternLayout
    PatternLayout(String pattern)
    Parameters:
    • pattern
      The conversion pattern string to use.

Top

XmlLayout

Based on log4j's XmlLayout, this layout formats a log message as a fragment of XML. An example of the format of the fragment is as follows:

<log4javascript:event logger="[default]" timestamp="1146007499" level="ERROR">
<log4javascript:message><![CDATA[Big problem!]]></log4javascript:message>
<log4javascript:exception><![CDATA[Nasty error on line number 1
	in file http://www.timdown.co.uk/index.php]]></log4javascript:exception>
</log4javascript:event>

Notes

  • This layout supports batching of log messages when used in an AjaxAppender. A batch of messages is simply concatenated to form a string of several XML frgaments similar to that above.
  • The <log4javascript:exception> element is only present if an exception was passed into the original log call.
  • As of version 1.3, custom fields may be added to the output. Each field will add a tag of the following form inside the <log4javascript:event> tag:

    <log4javascript:customfield name="sessionid"><![CDATA[1234]]></log4javascript:customfield>
    

Constructor

  • XmlLayout
    XmlLayout()

Top

JsonLayout

Formats a logging event into JavaScript Object Notation (JSON). This is the same as JavaScript's object literal syntax, meaning that log messages formatted with this layout can be interpreted directly by JavaScript and converted into objects. See json.org for more details about JSON.

Example:

{
	"logger": "[default]",
	"timeStamp": 1146008889,
	"level": "ERROR",
	"url": "http://localhost/timdown.co.uk/version_new/log4javascript/index.php",
	"message": "Big problem!",
	"exception": "Nasty error on line number 1 in file http://www.timdown.co.uk/index.php"
}

The exception property is only present if an exception was passed into the original log call.

Notes

  • This layout supports batching of log messages when used in an AjaxAppender. When sent singly the layout formats the log message as a single JavaScript object literal; when sent as a batch, the messages are formatted as an array literal whose elements are log message objects.
  • As of version 1.3, custom fields may be added to the output. Each field will add a property of the following form to the main object literal:

    	"sessionid": 1234
    

Constructor

  • JsonLayout
    JsonLayout(Boolean readable, String loggerKey, String timeStampKey, String levelKey, String messageKey, String exceptionKey, String urlKey)
    Parameters:
    • readable
      Whether or not to format each log message with line breaks and tabs. If not specified, defaults to false.
    • loggerKey
      Property name to use for the logger. If not specified, defaults to logger.
    • timeStampKey
      Property name to use for the log message timestamp. If not specified, defaults to timestamp.
    • levelKey
      Property name to use for the log message severity. If not specified, defaults to level.
    • messageKey
      Property name to use for the message string itself. If not specified, defaults to message.
    • exceptionKey
      Property name to use for the exception, if one is present in the logging event. If not specified, defaults to exception.
    • urlKey
      Property name to use for the URL of the referring page. If not specified, defaults to url.

Methods

  • setReadable
    void setReadable(Boolean readable)
    Sets whether or not to format each log message with line breaks and tabs.
  • isReadable
    Boolean isReadable()
    Returns whether or not to each log message is formatted with line breaks and tabs.

HttpPostDataLayout

Formats the log message as a simple URL-encoded string from which a simple server-side script may extract parameters such as the log message, severity and timestamp. This is the default layout for AjaxAppender.

Constructor

  • HttpPostDataLayout
    HttpPostDataLayout(String loggerKey, String timeStampKey, String levelKey, String messageKey, String exceptionKey, String urlKey)
    • loggerKey
      Parameter name to use for the logger. If not specified, defaults to logger.
    • timeStampKey
      Parameter name to use for the log message timestamp. If not specified, defaults to timestamp.
    • levelKey
      Parameter name to use for the log message severity. If not specified, defaults to level.
    • messageKey
      Parameter name to use for the message string itself. If not specified, defaults to message.
    • exceptionKey
      Parameter name to use for the exception, if one is present in the logging event. If not specified, defaults to exception.
    • urlKey
      Parameter name to use for the URL of the referring page. If not specified, defaults to url.

Notes

  • As of version 1.3, custom fields may be added to the output. Each field will be added as a parameter to the post data.

Top

Enabling / disabling log4javascript

All logging can be enabled or disabled in log4javascript in a number of ways:

  • At any time, you can call log4javascript.setEnabled(enabled). This will enable or disable all logging, depending on whether enabled is set to true or false.
  • Assign a value to the global variable log4javascript_disabled. The idea of this is so that you can enable or disable logging for a whole site by including a JavaScript file in all your pages, and allowing this file to be included before log4javascript.js to guarantee that no logging can take place without having to alter log4javascript.js itself. Your included .js file would include a single line such as the following:

    var log4javascript_disabled = true;

  • Assign your logger object a value of log4javascript.getNullLogger().
  • Replace your copy of log4javascript.js with log4javascript_stub.js, provided in the distribution. This file has a stub version of each of the functions and methods in the log4javascript API and can simply be dropped in in place of the main file. The compressed version of the stub is around 3Kb in size as opposed to 63Kb for the compressed version of the proper file.

Top

log4javascript error handling

log4javascript has a single rudimentary logger-like object of its own to handle messages generated by log4javascript itself. This logger is called LogLog.

Methods

  • setQuietMode
    void setQuietMode(Boolean quietMode)
    Parameters:
    • quietMode
      Whether to turn quiet mode on or off.
    Sets whether LogLog is in quiet mode or not. In quiet mode, no messages sent to LogLog have any visible effect. By default, quiet mode is switched off.
  • setShowAllErrors
    void setShowAllErrors(Boolean showAllErrors)
    Parameters:
    • showAllErrors
      Whether to show all errors or just the first.
    Sets how many errors LogLog will display alerts for. By default, only the first error encountered generates an alert to the user. If you turn all errors on by supplying true to this method then all errors will generate alerts.
  • debug
    void debug(String message, Error exception)
    Parameters:
    • message
    • exception [optional]
    Currently has no effect.
  • warn
    void warn(String message, Error exception)
    Parameters:
    • message
    • exception [optional]
    Currently has no effect.
  • error
    void error(String message, Error exception)
    Parameters:
    • message
    • exception [optional]
    Generates an alert to the user if and only if the error is the first one encountered and setShowAllErrors(true) has not been called.

Top

Differences between log4javascript and log4j

For the sake of keeping log4javascript light and useful, many of the features of log4j that seem over-complex or inappropriate for JavaScript have not been implemented. These include:

  • Filters
  • Configurators
  • Renderers

log4javascript allows for multiple loggers but does not carry over the idea of logger hierarchies and hence additivity of appenders from log4j; logger names carry no special significance in log4javascript, as it seems like overkill in JavaScript, which does not itself have the hierarchical package structure of Java that lends itself so nicely to log4j's logger hierarchy.

Top