Introduction

log4javascript currently exists to provide more flexible and configurable JavaScript logging
than that provided by browser developer tools. It works a very wide range of browsers. It was
originally written to ease the pain of JavaScript debugging in the days before browsers came
with advanced developer tools.

It requires only a JavaScript include and one line of code to initialize with default settings.
Having for several years used log4j and its .NET port log4net, it was natural for me to
base it on log4j.

AMD

Since version 1.4.10, log4javascript comes with AMD support hence can be loaded by a script
loader such as RequireJS.

The current version of JavaScript is designed only to run in a browser. If not using AMD,
log4javascript creates a single property of the global object (to all intents and purposes, a
global variable) called log4javascript.

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:

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

From version 1.4, configuring appenders is only possible via configuration
methods. As the number of configuration options increases it becomes increasingly
undesirable to use constructor parameters, so support for it has been dropped.

Example

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

First, log4javascript is initialized, and a logger (actually the
anonymous logger) is assigned to a variable called log:

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.

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:

log4javascript static properties/methods

Properties

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], [null]
and root are reserved for
the anonymous logger, default logger, null logger and root logger respectively.

getDefaultLogger

Logger getDefaultLogger()

Convenience method that returns the default logger. In the standard edition, the
default logger has a single appender: a
PopUpAppender with the default layout,
width and height, and with focusPopUp set to false and
lazyInit, useOldPopUp and
complainAboutPopUpBlocking all set to true.

In the production edition, the default logger has no appenders.

getNullLogger

Logger getNullLogger()

Returns an empty logger with no appenders. Useful for disabling all logging.

getRootLogger

Logger getRootLogger()

Returns the root logger from which all other loggers derive.

resetConfiguration

void resetConfiguration()

Resets the all loggers to their default level.

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.

addEventListener

void addEventListener(String eventType, Function listener)

Parameters:

eventType

listener

Adds a function to be called when an event of the type specified occurs in log4javascript.
Supported event types are load (occurs once the page has loaded) and
error.

Each listener is pased three paramaters:

sender. The object that raised the event (i.e. the log4javascript object);

eventType. The type of the event;

eventArgs. An object containing of event-specific arguments. For the error event,
this is an object with properties message and exception. For the load
event this is an empty object.

removeEventListener

void removeEventListener(String eventType, Function listener)

Parameters:

eventType

listener

Removes the event listener function supplied for the event of the type specified.

dispatchEvent

void dispatchEvent(String eventType, Object eventArgs)

Parameters:

eventType

eventArgs

Raises an event of type eventType on the log4javascript object.
Each of the listeners for this type of event (registered via addEventListener)
is called and passed eventArgs as the third parameter.

setEventTypes

void setEventTypes(Array eventTypes)

Parameters:

eventTypes

Used internally to specify the types of events that the log4javascript object can raise.

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 internal log4javascript variables and functions. This was written
for the purposes of automated testing but could be used by custom extensions to
log4javascript.

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.

Logger hierarchy and appender additivity

From version 1.4, log4javascript has hierarchical loggers, implemented in the same way
as log4j. In summary, you specify a logger's parent logger by means of a dot between the
parent logger name and the child logger name. Therefore the logger tim.app.security
inherits from tim.app, which in turn inherits from tim which,
finally, inherits from the root logger.

What inheritance means for a logger is that in the absence of a threshold level set
specifically on the logger it inherits its level from its parent; also, a logger inherits
all its parent's appenders (this is known as appender additivity in log4j. This
behaviour can be enabled or disabled via setAdditivity(). See below). In the
above example, if the root logger has a level of DEBUG and one appender,
each of the loggers tim.app.security, tim.app and tim would
inherit the root level's appender. If, say, tim.app's threshold level was set
to WARN, tim's effective level would remain at DEBUG
(inherited from the root logger) while tim.app.security's effective level would
be WARN, inherited from tim.app. The important thing to note is
that appenders accumulate down the logger hierarchy while levels are simply inherited from
the nearest ancestor with a threshold level set.

For a detailed explanation of the logger hierarchy, see the
log4j manual.

Notes

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

Logger methods

addAppender

void addAppender(Appender appender)

Parameters:

appender

Adds the given 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 level explicitly set for this logger or null if none has been set.

getEffectiveLevel

Level getEffectiveLevel()

Returns the level at which the logger is operating. This is either the level explicitly
set on the logger or, if no level has been set, the effective level of the logger's parent.

setAdditivity

void setAdditivity(Boolean additivity)

Parameters:

additivity

Sets whether appender additivity is enabled (the default) or disabled. If set to false, this
particular logger will not inherit any appenders form its ancestors. Any descendant of this
logger, however, will inherit from its ancestors as normal, unless its own additivity is
explicitly set to false.

Default value is true.

getAdditivity

Boolean getAdditivity()

Returns whether additivity is enabled for this logger.

log

void log(Level level, Object params)

Parameters:

level

params

Generic logging method used by wrapper methods such as debug,
error etc.

Starts a new group of log messages. In appenders that support grouping (currently
PopUpAppender and
InPageAppender), a group appears as an expandable
section in the console, labelled with the name specified.
Specifying initiallyExpanded determines whether the
group starts off expanded (the default is true). Groups may be nested.

groupEnd

void groupEnd()

Ends the current group. If there is no group then this function has no effect.

time

void time(String name, Level level)

Parameters:

name

level
[optional]

Starts a timer with name name. When the timer is ended with a
call to timeEnd using the same name, the amount of time that
has elapsed in milliseconds since the timer was started is logged at level
level. If not level is supplied, the level defaults to INFO.

timeEnd

void timeEnd(String name)

Parameters:

name

Ends the timer with name name and logs the time elapsed.

assert

void assert(Object expr)

Parameters:

expr

Asserts the given expression is true or evaluates to true.
If so, nothing is logged. If not, an error is logged at the ERROR level.

AlertAppender

Constructor

AjaxAppender

Editions: Standard, Production

A flexible appender that asynchronously sends log messages to a server via HTTP.

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.

From version 1.4, log message data is always sent as one or more name/value pairs.
In the case of HttpPostDataLayout,
data is sent the same as in previous versions. For other layouts such as
JsonLayout and
XmlLayout, the formatted log message is posted
as the value of a parameter called data, though this may be changed via
setPostVarName.

From version 1.4.5, it is possible to override this behaviour so that logging data
is sent as the request payload rather than as a posted form variable. This is done
by setting the Content-Type header sent with each Ajax request
explicitly. For example, if using a
JsonLayout:

ajaxApender.addHeader("Content-Type", "application/json");

From version 1.4, log message timestamps are sent as standard JavaScript times, i.e.
the number of milliseconds since 00:00:00 UTC on January 1, 1970.

Also from version 1.4, any outstanding log messages may optionally be sent when the
main page unloads (i.e. user follows a link, closes the window or refreshes the
page). This behaviour may be enabled using setSendAllOnUnload; see
below.

This behaviour is dependent on window.onbeforeunload; unfortunately,
Opera does not always raise this event, so this feature does not work reliably in
Opera.

From version 1.4.8, AjaxAppender supports the sending of cookies in CORS requests via
the new withCredentials constructor parameter.

Constructor

AjaxAppender

AjaxAppender(String url[, Boolean withCredentials])

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.

withCredentials

Since: 1.4.8

Specifies whether cookies should be sent with each request.

Methods

setSendAllOnUnload

void setSendAllOnUnload(Boolean sendAllOnUnload)

[not available after first message logged]

Whether to send all remaining unsent log messages to the server when the page
unloads.

Since version 1.4.3, the default value is false. Previously the
default was true.

Notes

This feature was found not to work prior to version 1.4.3 in WebKit
browsers (e.g. Google Chrome, Safari). As a result, a workaround was
implemented in 1.4.3 which has the unfortunate side effect of popping up a
confirmation dialog to the user if there are any log messages to send when
the page unloads. As a result, this feature is now obtrusive for the user
and is therefore disabled by default.

This feature does not work in any version of Opera.

isSendAllOnUnload

Boolean isSendAllOnUnload()

Returns whether all remaining unsent log messages are sent to the server when the page unloads.

setPostVarName

void setPostVarName(String postVarName)

[not available after first message logged]

Sets the post variable name whose value will the formatted log message(s) for
each request.

Returns the post variable name whose value will the formatted log message(s) for
each request.

setTimed

void setTimed(Boolean timed)

[not available after first message logged]

Whether to send log messages to the server at regular, timed intervals.

Default value is false.

isTimed

Boolean isTimed()

Returns whether log messages are sent to the server at regular, timed intervals.

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.

Default value is false.

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.

setBatchSize

void setBatchSize(Number batchSize)

[not available after first message logged]

Sets 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 more.
This also means that if the page unloads for any reason and sendAllOnUnload
is not set to true, 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 except when the
page unloads, if sendAllOnUnload is set to true.

getBatchSize

Number getBatchSize()

Returns the number of log messages sent in each request. See above 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.

Notes

timerInterval only has an effect in conjunction with
timed (set by setTimed(). 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.

getTimerInterval

Number getTimerInterval()

Returns the length of time in milliseconds between each sending of queued log
messages. See above for more details.

setRequestSuccessCallback

void setRequestSuccessCallback(Function requestSuccessCallback)

Sets the 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.

setFailCallback

void setFailCallback(Function failCallback)

Sets the 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.

setSessionId

void setSessionId(String sessionId)

Sets the session id sent to the server each time a request is made.

getSessionId

String getSessionId()

Returns the session id sent to the server each time a request is made.

addHeader

void addHeader(String name,
String value)

Adds an HTTP header that is sent with each request.

Since: 1.4.3

From 1.4.5, specifying the Content-Type header using this method
will force logging data to be sent as the Ajax request payload rather than as a
posted form field.

getHeaders

Array getHeaders()

Returns an array of the additional headers that are sent with each HTTP request.
Each array item is an object with properties name and
value.

Since: 1.4.3

sendAll

void sendAll()

Sends all log messages in the queue. If log messages are batched then only completed
batches are sent.

Constructor

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.

initiallyMinimized
[optional]

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

useDocumentWrite
[optional]

Specifies how the console window is created. By default, the console window is
created dynamically using document's write method. This has the
advantage of keeping all the code in one single JavaScript file. However, if your
page sets document.domain then the browser prevents script access to
a window unless it too has the same value set for document.domain. To
get round this issue, you can set useDocumentWrite to false
and log4javascript will instead use the external HTML file console.html
(or console_uncompressed.html if you're using an uncompressed version of
log4javascript.js), which must be placed in the same directory as your log4javascript.js file.

Note that if useDocumentWrite is set to true, the old pop-up
window will always be closed and a new one created whenever the page is refreshed, even
if setUseOldPopUp(true) has been called.

In general it's simpler to use the document.write method, so unless your
page needs to set document.domain, useDocumentWrite should
be set to true.

If not specified, defaults to true.

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.

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.

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. Default value is false.

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 the same pop-up window is used 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.

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 isUseOldPopUp above 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. Default value is true.

[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.
Default value is false (i.e. log messages are appended to the bottom of the 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. Default value is true.

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.
Default value is false.

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 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. Default value is null, which means no
limit is applied.

setMaxMessages

void setMaxMessages(Number maxMessages)

[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.

isShowCommandLine

Boolean isShowCommandLine()

Returns whether the console includes a command line.
Default value is true.

setShowCommandLine

void setShowCommandLine(Boolean showCommandLine)

Sets whether the console includes a command line.

getCommandLineObjectExpansionDepth

Number getCommandLineObjectExpansionDepth()

Returns the number of levels to expand when an object value is logged to the console.
Each property of an object above this threshold will be expanded if it is itself an object
or array, otherwise its string representation will be displayed. Default value is 1 (i.e.
the properties of the object logged will be displayed in their string representation but
not expanded).

setCommandLineObjectExpansionDepth:

void setCommandLineObjectExpansionDepth(Number expansionDepth)

Sets the number of levels to expand when an object value is logged to the console.

getCommandWindow

Window getCommandWindow()

Returns a reference to the window in which commands typed into the command line
are currently being executed.

setCommandWindow

void setCommandWindow(Window commandWindow)

Sets the window in which commands typed into the command line are executed.

getCommandLayout

Number getCommandLayout()

Returns the layout used to format the output for commands typed into the command line.
The default value is a PatternLayout with
pattern string %m

setCommandLayout

void setCommandLayout(Layout commandLayout)

Sets the layout used to format the output for commands typed into the command line.

clear

void clear()

Clears all messages from the console window.

close

void close()

Closes the pop-up window.

show

void show()

Opens the pop-up window, if not already open.

hide

void hide()

Closes the pop-up window.

focus

void focus()

Brings the console window to the top and gives it the focus.

focusCommandLine

void focusCommandLine()

Brings the console window to the top and gives the focus to the command line.

focusSearch

void focusSearch()

Brings the console window to the top and gives the focus to the search box.

Constructor

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.

initiallyMinimized
[optional]

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

Specifies how the console window is created. By default, the console window is
created dynamically using document's write method. This has the
advantage of keeping all the code in one single JavaScript file. However, if your
page sets document.domain then the browser prevents script access to
a window unless it too has the same value set for document.domain. To
get round this issue, you can set useDocumentWrite to false
and log4javascript will instead use the external HTML file console.html
(or console_uncompressed.html if you're using an uncompressed version of
log4javascript.js), which must be placed in the same directory as your log4javascript.js file.

In general it's simpler to use the document.write method, so unless your
page needs to set document.domain, useDocumentWrite should
be set to true.

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.

Methods

addCssProperty

void addCssProperty(String name, String value)

Sets a CSS style property on the HTML element containing the console iframe.

isVisible

Boolean isVisible()

Returns whether the console window is currently visible.

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 maxMessages)

[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.

isShowCommandLine

Boolean isShowCommandLine()

Returns whether the console includes a command line.
Default value is true.

setShowCommandLine

void setShowCommandLine(Boolean showCommandLine)

Sets whether the console includes a command line.

getCommandLineObjectExpansionDepth

Number getCommandLineObjectExpansionDepth()

Returns the number of levels to expand when an object value is logged to the console.
Each property of an object above this threshold will be expanded if it is itself an object
or array, otherwise its string representation will be displayed. Default value is 1 (i.e.
the properties of the object logged will be displayed in their string representation but
not expanded).

setCommandLineObjectExpansionDepth:

void setCommandLineObjectExpansionDepth(Number expansionDepth)

Sets the number of levels to expand when an object value is logged to the console.

getCommandWindow

Window getCommandWindow()

Returns a reference to the window in which commands typed into the command line
are currently being executed.

setCommandWindow

void setCommandWindow(Window commandWindow)

Sets the window in which commands typed into the command line are executed.

getCommandLayout

Number getCommandLayout()

Returns the layout used to format the output for commands typed into the command line.
The default value is a PatternLayout with
pattern string %m

setCommandLayout

void setCommandLayout(Layout commandLayout)

Sets the layout used to format the output for commands typed into the command line.

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.

Notes

From version 1.4, the custom field value may be a function. In this
case, the function is run at the time the layout's format method is called,
with the following two parameters:

Constructor

PatternLayout

Editions: All

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

a

Outputs log messages specified as an array.

Behaves exactly like %m, except that multiple log messages are
assumed to have been specified in the logging call as an array rather than
as multiple parameters.

Since: 1.4

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 log messages of the logging event (i.e. the log
messages supplied by the client code).

As of version 1.4, multiple log messages may be supplied to logging calls.
%m displays each log message (using the rules below) one after
another, separated by spaces.

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.

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.4, timestamps are returned as milliseconds since midnight of
January 1, 1970 rather than seconds as in previous versions. This allows finer
measurement of the time a logging event occurred and is also the JavaScript
Date object's standard measurement.

Also as of version 1.4, multiple messages may be specified as separate parameters
in a single logging call. In XmlLayout, multiple messages may be
formatted as a single combined message or may be formated as several
<log4javascript:message> elements inside one
<log4javascript:messages> element as shown below:

Constructor

XmlLayout

XmlLayout([Boolean combineMessages])

combineMessages

Whether or not to format multiple log messages as a combined single
<log4javascript:message> element
composed of each individual message separated by line breaks or to include
a <log4javascript:message> element for each message inside
one <log4javascript:messages> element.
If not specified, defaults to true.

JsonLayout

Editions: Standard, Production

Formats a logging event into JavaScript Object Notation (JSON).
JSON is a subset of 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.

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

From version 1.4, the variable names used for log event properties such as
the message, timestamp and exception are specified using the setKeys()
method of Layout.

Also as of version 1.4, multiple messages may be specified as separate parameters
in a single logging call. In JsonLayout, multiple messages may be
formatted as a single combined message or may be formated as an array of messages
as shown below:

Constructor

Whether or not to format each log message with line breaks and tabs.
If not specified, defaults to false.

combineMessages

Whether or not to format multiple log messages as a combined single
message property composed of each individual message separated by line
breaks or to format multiple messages as an array.
If not specified, defaults to true.

Methods

isReadable

Boolean isReadable()

Returns whether or not to each log message is formatted with line breaks and tabs.

Notes

setReadable has been removed in version 1.4. This property can
be set via the constructor.

HttpPostDataLayout

Editions: Standard, Production

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()

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.

From version 1.4, the variable names used for log event properties such as
the message, timestamp and exception are specified using the setKeys()
method of Layout.

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_x.js with stubs/log4javascript_x.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 typically 15 times smaller than the
compressed version of the main file.

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
and is accessed via log4javascript.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.

setAlertAllErrors

void setAlertAllErrors(Boolean alertAllErrors)

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]

Logs a debugging message to an in-memory list. This implementation is new in version 1.4.

displayDebug

void displayDebug()

Displays an alert of all debugging messages. This method is new in version 1.4.

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 setAlertAllErrors(true) has not been called.