log4javascript 1.4 manual
Contents
- Introduction
- AMD
- Note about the log4javascript object
- Loggers, appenders, layouts and levels
- log4javascript static properties/methods
- Levels
- Loggers
- Appenders
- Layouts
- Enabling / disabling log4javascript
- log4javascript error handling
- Differences between log4javascript and log4j
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:
var popUpAppender = new log4javascript.PopUpAppender();
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
:
<script type="text/javascript" src="log4javascript.js"></script> <script type="text/javascript"> //<![CDATA[ var log = log4javascript.getLogger();
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(); 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)
log4javascript static properties/methods
Properties
-
versionThe version number of your copy of log4javascript.
-
editionThe edition of your copy of log4javascript.
-
logLoglog4javascript'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 togetLogger()
(with no logger name specified) will return this same logger object.Note that the names
[anonymous]
,[default]
,[null]
androot
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 withfocusPopUp
set to false andlazyInit
,useOldPopUp
andcomplainAboutPopUpBlocking
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 onenabled
. -
-
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) anderror
.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 theerror
event, this is an object with propertiesmessage
andexception
. For theload
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 typeeventType
on thelog4javascript
object. Each of the listeners for this type of event (registered viaaddEventListener
) is called and passedeventArgs
as the third parameter. -
-
setEventTypes
void setEventTypes(Array eventTypes)
Parameters:-
eventTypes
Used internally to specify the types of events that thelog4javascript
object can raise. -
-
setShowStackTraces
void setShowStackTraces(Boolean show)
Parameters:-
show
Enables or disables displaying of error stack traces, depending onshow
. 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. -
Levels
Levels are available as static properties of the log4javascript.Level
object. In ascending order of severity:
log4javascript.Level.ALL
log4javascript.Level.TRACE
log4javascript.Level.DEBUG
log4javascript.Level.INFO
log4javascript.Level.WARN
log4javascript.Level.ERROR
log4javascript.Level.FATAL
log4javascript.Level.OFF
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
orgetNullLogger
.
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 thanlevel
will not be logged. Default value isDEBUG
. -
-
getLevel
Level getLevel()
Returns the level explicitly set for this logger ornull
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 asdebug
,error
etc.Notes
- The signature of this method has changed in 1.4.
-
-
trace
void trace(Object message1[, Object message2, ... ][, Error exception])
Parameters:-
message1[, message2...]
-
exception
[optional]
Logs one or more messages and optionally an error at levelTRACE
.Notes
- Logging of multiple messages in one call is new in 1.4.
-
-
debug
void debug(Object message1[, Object message2, ... ][, Error exception])
Parameters:-
message1[, message2...]
-
exception
[optional]
Logs one or more messages and optionally an error at levelDEBUG
.Notes
- Logging of multiple messages in one call is new in 1.4.
-
-
info
void info(Object message1[, Object message2, ... ][, Error exception])
Parameters:-
message1[, message2...]
-
exception
[optional]
Logs one or more messages and optionally an error at levelINFO
.Notes
- Logging of multiple messages in one call is new in 1.4.
-
-
warn
void warn(Object message1[, Object message2, ... ][, Error exception])
Parameters:-
message1[, message2...]
-
exception
[optional]
Logs one or more messages and optionally an error at levelWARN
.Notes
- Logging of multiple messages in one call is new in 1.4.
-
-
error
void error(Object message1[, Object message2, ... ][, Error exception])
Parameters:-
message1[, message2...]
-
exception
[optional]
Logs one or more messages and optionally an error at levelERROR
.Notes
- Logging of multiple messages in one call is new in 1.4.
-
-
fatal
void fatal(Object message1[, Object message2, ... ][, Error exception])
Parameters:-
message1[, message2...]
-
exception
[optional]
Logs one or more messages and optionally an error at levelFATAL
.Notes
- Logging of multiple messages in one call is new in 1.4.
-
-
isEnabledFor
Boolean isEnabledFor(Level level, Error exception)
Parameters:-
level
Returns whether the logger is enabled for the specified level. -
-
isTraceEnabled
Boolean isTraceEnabled()
Returns whether the logger is enabled forTRACE
messages. -
isDebugEnabled
Boolean isDebugEnabled()
Returns whether the logger is enabled forDEBUG
messages. -
isInfoEnabled
Boolean isInfoEnabled()
Returns whether the logger is enabled forINFO
messages. -
isWarnEnabled
Boolean isWarnEnabled()
Returns whether the logger is enabled forWARN
messages. -
isErrorEnabled
Boolean isErrorEnabled()
Returns whether the logger is enabled forERROR
messages. -
isFatalEnabled
Boolean isFatalEnabled()
Returns whether the logger is enabled forFATAL
messages. -
group
void group(String name, Boolean initiallyExpanded)
Parameters:-
name
-
initiallyExpanded
[optional]
Starts a new group of log messages. In appenders that support grouping (currentlyPopUpAppender
andInPageAppender
), a group appears as an expandable section in the console, labelled with thename
specified. SpecifyinginitiallyExpanded
determines whether the group starts off expanded (the default istrue
). 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 namename
. When the timer is ended with a call totimeEnd
using the same name, the amount of time that has elapsed in milliseconds since the timer was started is logged at levellevel
. If not level is supplied, the level defaults toINFO
. -
-
timeEnd
void timeEnd(String name)
Parameters:-
name
Ends the timer with namename
and logs the time elapsed. -
-
assert
void assert(Object expr)
Parameters:-
expr
Asserts the given expression istrue
or evaluates totrue
. If so, nothing is logged. If not, an error is logged at theERROR
level. -
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. Every appender object 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. Every appender object should implement this method.
AlertAppender
Editions: Standard
Displays a log message as a JavaScript alert.
Constructor
-
AlertAppender
AlertAppender()
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
areJsonLayout
andXmlLayout
, 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 implementedsetRequestHeader
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. -
The default layout is
HttpPostDataLayout
. -
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 asJsonLayout
andXmlLayout
, the formatted log message is posted as the value of a parameter calleddata
, though this may be changed viasetPostVarName
.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 aJsonLayout
: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 wastrue
.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.
Default value is
data
.Notes
-
This has no effect if the current layout is an
HttpPostDataLayout
.
-
This has no effect if the current layout is an
-
getPostVarName
String getPostVarName()
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 totrue
, 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, ifsendAllOnUnload
is set totrue
.
-
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
-
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 withtimed
(set bysetTimed()
. Iftimed
is set to false thentimerInterval
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 totrue
, 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 propertiesname
andvalue
.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.
PopUpAppender
Editions: Standard
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 unwanted 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;
- grouped log messages. Groups may be nested and each has a button to show or hide the log messages in that group;
- clear button to allow user to delete all current log messages.
-
command prompt with up/down arrow history. Command line functions may be added
to the appender. Several command line functions are built in:
-
$(String id)
Prints a string representation of a single element with the id supplied. -
dir(Object obj)
Prints a list of a properties of the object supplied. -
dirxml(HTMLElement el)
Prints the XML source code of an HTML or XML element -
cd(Object win)
Changes the scope of execution of commands to the named frame or window (either a window/frame name or a reference to a window object may be supplied). -
clear()
Clears the console. -
keys(Object obj)
Prints a list of the names of all properties of the object supplied. -
values(Object obj)
Prints a list of the values of all properties of the object supplied. -
expansionDepth(Number depth)
Sets the number of levels of expansion of objects that are displayed by the command line. The default value is 1.
-
Notes
-
The default layout for this appender is
PatternLayout
with pattern string%d{HH:mm:ss} %-5p - %m{1}%n
Constructor
-
PopUpAppender
PopUpAppender([Boolean lazyInit, Boolean initiallyMinimized, Boolean useDocumentWrite, Number width, Number height])
Parameters:-
lazyInit
[optional]Set this totrue
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 tofalse
. -
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
'swrite
method. This has the advantage of keeping all the code in one single JavaScript file. However, if your page setsdocument.domain
then the browser prevents script access to a window unless it too has the same value set fordocument.domain
. To get round this issue, you can setuseDocumentWrite
tofalse
and log4javascript will instead use the external HTML fileconsole.html
(orconsole_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 totrue
, the old pop-up window will always be closed and a new one created whenever the page is refreshed, even ifsetUseOldPopUp(true)
has been called.In general it's simpler to use the
document.write
method, so unless your page needs to setdocument.domain
,useDocumentWrite
should be set totrue
.If not specified, defaults to
true
. -
width
[optional]The outer width in pixels of the pop-up window. If not specified, defaults to600
. -
height
[optional]The outer height in pixels of the pop-up window. If not specified, defaults to400
.
-
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 isfalse
. -
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 totrue
.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. SeeisUseOldPopUp
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 istrue
. -
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. Default value isfalse
(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 istrue
. -
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 isfalse
. -
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 isnull
, 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 tonull
to make this number unlimited. -
isShowCommandLine
Boolean isShowCommandLine()
Returns whether the console includes a command line. Default value istrue
. -
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 aPatternLayout
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. -
evalCommandAndAppend
void evalCommandAndAppend(String expr)
Evaluates the expression and appends the result to the console. -
addCommandLineFunction
void addCommandLineFunction(String functionName, Function commandLineFunction)
Adds a function with the name specified to the list of functions available on the command line. This feature may be used to add custom functions to the command line.
When you call the function on the command line,
commandLineFunction
is executed with the following three parameters:- appender. A reference to the appender in which the command was executed;
- args.
An array-like list of parameters passed into the function on the command line
(actually a reference to the
arguments
object representing the parameters passed into the function by the user); - returnValue. This is an object with two properties that allow the function to control
how the result is displayed:
- appendResult. A boolean value that determines whether the returned value from this
function is appended to the console. The default value is
true
; - isError. A boolean value that specifies whether the output of this function
should be displayed as an error. The default value is
false
.
- appendResult. A boolean value that determines whether the returned value from this
function is appended to the console. The default value is
The value returned by the function is formatted by the command layout and appended to the console.
InPageAppender
Editions: Standard
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 and later as an alias for InPageAppender.
-
The default layout for this appender is
PatternLayout
with pattern string%d{HH:mm:ss} %-5p - %m{1}%n
Constructor
-
InPageAppender
InPageAppender(HTMLElement container[, Boolean lazyInit, Boolean initiallyMinimized, Boolean useDocumentWrite, String width, String height])
Parameters:-
container
The container element for the console window. This should be an HTML element. -
lazyInit
[optional]Set this totrue
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 totrue
. -
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.
-
In Safari (and possibly other browsers) hiding an
-
useDocumentWrite
[optional]Specifies how the console window is created. By default, the console window is created dynamically using
document
'swrite
method. This has the advantage of keeping all the code in one single JavaScript file. However, if your page setsdocument.domain
then the browser prevents script access to a window unless it too has the same value set fordocument.domain
. To get round this issue, you can setuseDocumentWrite
tofalse
and log4javascript will instead use the external HTML fileconsole.html
(orconsole_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 setdocument.domain
,useDocumentWrite
should be set totrue
.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 to100%
. -
height
[optional]The height of the console window. Any valid CSS length may be used. If not specified, defaults to250px
.
-
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 tonull
to make this number unlimited. -
isShowCommandLine
Boolean isShowCommandLine()
Returns whether the console includes a command line. Default value istrue
. -
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 aPatternLayout
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. -
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.
-
In Safari (and possibly other browsers), hiding an
-
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.
-
In Safari (and possibly other browsers), hiding an
-
close
void close()
Removes the console window iframe from the main document. -
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. -
evalCommandAndAppend
void evalCommandAndAppend(String expr)
Evaluates the expression and appends the result to the console. -
addCommandLineFunction
void addCommandLineFunction(String functionName, Function commandLineFunction)
Adds a function with the name specified to the list of functions available on the command line. This feature may be used to add custom functions to the command line.
When you call the function on the command line,
commandLineFunction
is executed with the following three parameters:- appender. A reference to the appender in which the command was executed;
- args.
An array-like list of parameters passed into the function on the command line
(actually a reference to an
arguments
object); - returnValue. This is an object with two properties that allow the function to control
how the result is displayed:
- appendResult. A boolean value that determines whether the returned value from this
function is appended to the console. The default value is
true
; - isError. A boolean value that specifies whether the output of this function
should be displayed as an error. The default value is
false
.
- appendResult. A boolean value that determines whether the returned value from this
function is appended to the console. The default value is
The value returned by the function is formatted by the command layout and appended to the console.
BrowserConsoleAppender
Editions: Standardl
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 toWARN
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
-> Firebugdebug
- log4javascript
INFO
-> Firebuginfo
- log4javascript
WARN
-> Firebugwarn
- log4javascript
ERROR
,FATAL
-> Firebugerror
... 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. - log4javascript
Constructor
-
BrowserConsoleAppender
BrowserConsoleAppender()
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 itsformat
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
andXmlLayout
are the only built-in 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 islogger
. -
timeStampKey
Parameter to use for the log message's timestamp. Default istimestamp
. -
levelKey
Parameter to use for the log message's level. Default islevel
. -
messageKey
Parameter to use for the message itself. Default ismessage
. -
exceptionKey
Parameter to use for the log message's error (exception). Default isexception
. -
urlKey
Parameter to use for the current page URL. Default isurl
.
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 areJsonLayout
andHttpPostDataLayout
. -
-
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
andXmlLayout
) 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 withvalue
.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:
- layout. A reference to the layout being used;
- loggingEvent. A reference to the logging event being formatted.
-
-
hasCustomFields
Boolean hasCustomFields()
Returns whether the layout has any custom fields.
NullLayout
Editions: All
The most basic layout. NullLayout's format()
methods performs no
formatting at all and simply returns the message logged.
Constructor
-
NullLayout
NullLayout()
SimpleLayout
Editions: Standard, Production
Provides 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()
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 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,
The date format specifier is the same as that used by Java's
|
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.
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, |
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_PATTERNBuilt-in conversion pattern, equivalent to
%r %p %c - %m%n
. -
DEFAULT_CONVERSION_PATTERNBuilt-in conversion pattern, equivalent to
%m%n
. -
ISO8601_DATEFORMATBuilt-in date format (and also the default), equivalent to
yyyy-MM-dd HH:mm:ss,SSS
. -
DATETIME_DATEFORMATBuilt-in date format, equivalent to
dd MMM YYYY HH:mm:ss,SSS
. -
ABSOLUTETIME_DATEFORMATBuilt-in date format, equivalent to
HH:mm:ss,SSS
.
Constructor
-
PatternLayout
PatternLayout(String pattern)
Parameters:-
pattern
The conversion pattern string to use.
-
XmlLayout
Editions: Standard, Production
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="1201048234203" level="ERROR"> <log4javascript:message><![CDATA[Big problem!]]></log4javascript:message> <log4javascript:exception><![CDATA[Nasty error on line number 1 in file http://log4javascript.org/test.html]]></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.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:
<log4javascript:event logger="[default]" timestamp="1201048234203" level="ERROR"> <log4javascript:messages> <log4javascript:message><![CDATA[Big problem!]]></log4javascript:message> <log4javascript:message><![CDATA[Value of x when this error occurred: 3]]></log4javascript:message> </log4javascript:messages> <log4javascript:exception><![CDATA[Nasty error on line number 1 in file http://log4javascript.org/test.html]]></log4javascript:exception> </log4javascript:event>
-
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([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 totrue
.
-
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.
Example:
{ "logger": "[default]", "timeStamp": 1201048234203, "level": "ERROR", "url": "http://log4javascript.org/test.html", "message": "Big problem!", "exception": "Nasty error on line number 1 in file http://log4javascript.org/test.html" }
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 ofLayout
. -
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:{ "logger": "[default]", "timeStamp": 1201048234203, "level": "ERROR", "url": "http://log4javascript.org/test.html", "message": [ "Big problem!", "Value of x when this error occurred: 3" ], "exception": "Nasty error on line number 1 in file http://log4javascript.org/test.html" }
Constructor
-
JsonLayout
JsonLayout([Boolean readable, Boolean combineMessages])
Parameters:-
readable
Whether or not to format each log message with line breaks and tabs. If not specified, defaults tofalse
. -
combineMessages
Whether or not to format multiple log messages as a combined singlemessage
property composed of each individual message separated by line breaks or to format multiple messages as an array. If not specified, defaults totrue
.
-
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 ofLayout
.
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 whetherenabled
is set totrue
orfalse
. -
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 whetherLogLog
is in quiet mode or not. In quiet mode, no messages sent toLogLog
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 errorsLogLog
will display alerts for. By default, only the first error encountered generates an alert to the user. If you turn all errors on by supplyingtrue
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 andsetAlertAllErrors(true)
has not been called. -
Differences between log4javascript and log4j
For the sake of keeping log4javascript as light and useful as possible, many of the features of log4j that seem over-complex or inappropriate for JavaScript have not been implemented. These include:
- Filters
- Configurators
- Renderers