Adding request headers
- Working demo code: JSNLogDemo_Log4Net_beforeSend.
You may want to add request headers to the log request to the server, keep track of the success or failure of the log request, etc.
To make that happen, assign a function to the beforeSend appender option in your JavaScript code using the setOptions method.
beforeSend
The beforeSend option lets you set a function that is called right before an AJAX request with log messages is sent to the server. It receives these parameters:
beforeSend(xhr: XMLHttpRequest, json: any)
xhr | XMLHttpRequest object used to send the request. Allows you to for example add your own request headers. |
---|---|
json | Message to be sent. Allows you to modify this message before it is sent. See below. |
The message passed in via the json parameter has this format:
{ r: "request id", // Obsolete. May be empty string. lg: [ { l: level, m: 'message', n: 'logger name', t: timestamp, u: event id }, ... ] }
Please note that a single JSON message to the server can contain multiple log messages. This is because the AJAX appender can be configured to batch messages, for example 2 log messages per JSON message to the server.
About the individual fields:
Field | Description |
---|---|
request id | Obsolete. Do not use. |
level | Numeric severity of the log message. |
message | Message to be logged. |
logger name | Name of the logger. |
timestamp | The time the message was logged by your JavaScript. This is the number of milliseconds since 1 January 1970 00:00:00 UTC, according to the client machine's clock. |
event id | Number that uniquely identifies the event within the request. |
To set a default beforeSend method for all ajax appenders,
set the library wide option
JL.defaultBeforeSend
Caution
JSNLog uses the
onreadystatechange and
status properties of the
XMLHttpRequest object
to detect whether the response to a log request was received. That allows is to
deal with losing the Internet connection
Your beforeSend method will be called after jsnlog.js has set its own onreadystatechange handler. This means that if you decide to set your own onreadystatechange handler, make it call the original onreadystatechange handler in addition to your own functionality, so jsnlog.js can continue handling connection lost situations.
Example: Add request headers
Ensure that an additional request header myheader with value myvalue is added to every log request to the server.
// Create beforeSend handler var beforeSendExample = function (xhr) { xhr.setRequestHeader('myheader', 'myvalue'); }; // Create appender that uses beforeSendExample var appender = JL.createAjaxAppender("example appender"); appender.setOptions({ "beforeSend": beforeSendExample }); // Get all loggers to use this appender JL().setOptions({ "appenders": [appender] });