Giter Club home page Giter Club logo

jsnlog.js's Introduction

JSNLog.js

JSNLog.js is a tiny (2kb min+gz) JavaScript logging library.

  • It has lots of options to reduce the amount of log data, so you get only the data you need.
  • It sends log data to the server where you can store it.

Details and documentation: js.jsnlog.com

License: MIT

Integrate with server side logging

  • JSNLog for .Net - Combines jsnlog.js with a .Net handler to automatically store client side log data in your server side logs. Supports Log4net, Nlog, Elmah, Common.Logging. Also lets you configure client side loggers in your web.config.
  • JSNLog for PHP - PHP handler that receives log data from JSNLog.js and stores it on the server.
  • JSNLog for Node.js - Use jsnlog.js on both the client and the server. Client side log messages are sent to the server where they are stored in your server side logs. Supports Winston transports.
  • Open an issue if you want to build a server side handler for another language.

jsnlog.js's People

Contributors

mperdeck avatar almenit avatar bogdanicis avatar watsoncj avatar mathuf avatar neooleg avatar terribledev avatar txavier avatar

Stargazers

shunia avatar Vladimir avatar Ruslan Konviser avatar Gurdev avatar Guven Ozyurt avatar  avatar K. N. avatar Rex Tsang avatar  avatar Bryden Wayne avatar Sean Li avatar Mohammad Javad Ebrahimi avatar  avatar  avatar Pablo Novas avatar Thomas Theunen avatar Ares avatar  avatar Shell Yu avatar Marko Zorec avatar Javen Fang avatar Konstantsin Demedenkov avatar Rohan Talip avatar Samuel Philipp avatar 大関 金城 秀喜 カシオ avatar  avatar PsAiL avatar Matt Lehner avatar  avatar Mike Nason avatar  avatar Mohammad Esfandiari avatar Tim Lam avatar  avatar Mathews avatar Chris Fasel avatar Fabio Dias Rollo avatar Tobi Schäfer avatar Rod Kisten (Costa) avatar Zhang Gong avatar Svetoslav avatar Anders Fajersson avatar Pelle Wessman avatar TotPeRo avatar Pervez Goiporia avatar Rick Rickards avatar James M Irvine avatar Eyal Zekaria avatar Vasiliy Faronov avatar Naz avatar Lakshminp avatar Mel Massadian avatar Johnson Chetty avatar Andrey Kudashkin avatar Andrew Cavalcante Pacífico avatar Ronald CK Poon avatar Jekyll avatar ltchronus avatar Uğur ÖZGEN avatar Ethan Resnick avatar Leif Olsen avatar Diego Verbrugghe avatar Moose avatar Aleksandr avatar Luke Clark avatar cheahkhing avatar Alexey Karpov avatar Lukas Shawford avatar Matej Kramny avatar D See Ker avatar Leooolin avatar James Irwin avatar Byron Thanopoulos avatar Matt Tortolani avatar Ilya Ayzenshtok avatar Cameron Chapman avatar Serg avatar Harrison Powers avatar Norman Sue avatar Roger Mattos avatar Viktor Szépe avatar David Chase avatar Marwan Hilmi avatar Joe Tremblay avatar Bhavin Patel avatar Rai Butera avatar Suntharesan Mohan avatar Lynn Wallenstein avatar Vadim S avatar Nejuf Rowan avatar Child Wang World avatar Nico avatar Roman Nikitin avatar Anselmo Silva avatar creynders avatar Thiago F avatar Ben Plessinger avatar  avatar  avatar Cory Silva avatar

Watchers

Serg avatar James Cloos avatar  avatar  avatar  avatar Andrey Kudashkin avatar  avatar  avatar Harshit Gupta avatar

jsnlog.js's Issues

Add sequence number

When two items get logged right after each other, their JavaScript timestamps may be the same. But there is no guarantee that they arrive at the server in the right order. If this happens when logging parameters on a series of function calls, that can get very confusing.

Have a central sequence number (shared by all appenders) that assigns a seq nbr to all log items in increasing order. That way, each log item has a sequence number that is unique per request.

AMD usage with Dojo

On line 968, the AMD module gets defined with the module name as the first parameter. This is supported in RequireJS, but not in other AMD loaders, specifically Dojo. To get jsnlog.js to load with Dojo, I had to remove the name. Could this be updated/fixed in future releases?

sourcemaps

Hey,
thank you very much for creating this great tiny library. It does serve me very well and has reported plenty of errors in the past.

However, since I started optimizing my javascript code with uglify.js and transpiling from ES6 the stack traces are not that useful anymore.
Is there a way to map the stack trace to the original js files with sourcemaps?
Looking through the docs I did not find such an option.

Cheers

Newbie needs help setting server URL

Thank you for the efforts. I am excited to use this in my project.

var logger = JL();
logger.setOptions({
  "defaultAjaxUrl": "/assets/php/jsnlogger.php"
});
logger.fatal('test message');

I tried this, but it is still trying to send log error messages to /jsnlog.logger. What am I doing wrong?

Issue in compiled JS

Hello,

2.17.0 seems to have reverted some previous changes (made just hours before) to the javascript file, specifically in how __extends is defined.

This is a breaking issue when used via babel in some environments, as this.__extends is replaced with undefined.__extends

I suspect it is a typescript compiler version issue, as compiling this locally with the latest compiler produces the earlier version.

Relevant lines:

2.17.0: 3853663
var __extends = this.__extends || function (d, b) {
Earlier commit: 0236881
var __extends = (this && this.__extends) || function (d, b) {

error TS1127: Invalid character

Hi,

I installed jsnlog for node js + angular 4 env, and when I imported the log like this in my code:

import { JL } from 'jsnlog';

and compiled, I got bunch of errors like these:

ERROR in ...\node_modules\jsnlog\Definitions\jl.d.ts
(1,1): error TS1127: Invalid character.

To fix it, I updated the jl.d.ts file and removed first few lines of comments, and the code compiled. I presume there is some invalid unicode in the file (I am using Windows 10), which caused the issue.

Thanks

The format of the posted data (FormData, JSON)

Hello!

The PHP JSNLog logger on the server side reads raw POST data and know it to be JSON to parse.

However, our app (or rather the PHP engine) that the logger is incorporated in, expects POST data to be in FormData format, and parses it as such (and presents it in the $_POST superglobal array).

As a result, in some cases $_POST array may contain some random data as parsed out of the data sent by JL. For example, a request from JS:
JL('onerrorLogger').fatalException('?confirm=1&action=doit&redirect=1')
populates $_POST with:

$_POST = Array
(
    [{"r":"","lg":_{"l":6000,"m":"?confirm] => 1
    [action] => doit
    [redirect] => 1","n":"onerrorLogger","t":1483118770674}]}
)

You can see that debugging data may accidentally become a request to "action=doit".

What would be the best solution here?

Ability to prepend ALL log messages

Hi,

I'm looking for the ability to define a function that appends/prepends all log messages with some user data that is only available on the client side. Maybe another setOptions property. I was hoping I could get the body of the XmlHttpRequest in beforeSend, but it's not available there.

The closest I can find is adding a header with the data I want to send, but then I'm not sure how to get log4net to use that header data. I've looked into the EmptyLog4Net - beforeSend project, but the customer header doesn't appear to be used anywhere after it's sent.

Thanks,
Ashley

Should handle un-caught rejected promises

At the moment if an error is produced within a Promise then this won't be caught, as by default these aren't bubbled up to the onerror. onunhandledrejection should be also listened to such that these issues can be reported. e.g.

(function () {

    // Create onerror handler to log uncaught exceptions to the server side log, but only if there 
    // is no such handler already.
    // Must use "typeof window" here, because in NodeJs, window is not defined at all, so cannot refer to window in any way.
    if (typeof window !== 'undefined' && !window.onunhandledrejection) {
        window.onunhandledrejection = function (event) {

            // Send object with all data to server side log, using severity fatal, 
            // from logger "onerrorLogger"
            JL("onerrorLogger").fatalException({
                "msg": "unhandledrejection",
                "errorMsg": event.reason.message
            }, event.reason);

            // Tell browser to run its own error handler as well   
            return false;
        };
    }
})();

Modifying json sent using AjaxAppender

I wanted to update the json sent to the server, which uses Ajaxappender. Can this be done?
The main reason being i dont want to send the log level code but send the log level itself, i.e. ERROR, WARN etc.

Using in Office 365

I am trying to use this in office 365 for catching fatal error and send to Azure service where log4net is configured along with jsnlog.log4net.

From the client side, console i can see -
Uncaught ReferenceError: JL is not defined

It seems that, i am missing something. Is there any sample for logging in Office 365 environment.

Disable the logger

Hello,
How can I disable the logger ? I want the logger to be enabled only on production.

Error when building with webpack in angular-cli project

When using jsnlog in an Angular project (generated with @angular/cli 1.2.6) building for production and ahead-of-time (ng build --prod --aot), the build process can't resolve the module.

ERROR in ./src/$$_gendir/app/app.module.ngfactory.ts 
Module not found: Error: Can't resolve 'jsnlog/Definitions/jl' in 'C:\Users\Name\Code\JSNLogWebpack\src\$$_gendir\app'
 @ ./src/$$_gendir/app/app.module.ngfactory.ts 13:0-44
 @ ./src/main.ts
 @ multi ./src/main.ts

Building with ng build is completing without an error.

I generated a sample project: https://github.com/hzahradnik/JSNLogWebpack

Support timing and profiling

Add capability to loggers to start and end a timing block.
The loggers at each end of the block will have the same name (creating the association between the two).
In console appender, they create a group, to make it easy to see the timing block.

In console appender, where possible they do profiling (console.profiling, avail on firebug)

Opion to always send the time elapsed, or to only send message on timeout (took too long).

Something like
JL().info().startTimer()
...
JL().info("time taken by ... is").sendElapsedTime()

or

JL().info().startTimer()
...
JL().error("time taken by ... is too long:").sendTimeOut(timeOutInMs: int)

Store batch buffer in localstorage

Objective is for the buffer to survive page refreshes. So if the connection to the server is lost but the user keeps surfing locally, the log entries are not lost for ever.

RequestId not sent in header

Adding the RequestId in the options:

JL().setOptions({
        "requestId": "35F7416D-86F1-47FA-A9EC-547FFF510086",
        "appenders": [this.appender]
    });

Does not send the requestId in the header of the http Request:
image

XMLHttpRequest cannot load http://localhost/api/log. Request header field JSNLog-RequestId is not allowed by Access-Control-Allow-Headers.

Hi All,

I am getting the below error after using the below code in my project.Could you please help out?

Error:
XMLHttpRequest cannot load http://localhost:8083/api/log. Request header field JSNLog-RequestId is not allowed by Access-Control-Allow-Headers.

Code:
window.onerror = function( msg, url, lineNo,errorObj)
{
JL("onerrorLogger").fatalException({
"msg": "Exception!",
"errorMsg": msg, "url": url,
"line number": lineNo
}, errorObj);

    // return true to stop error from propogating, false to allow propogation
    return true; 
};

var appender = JL.createAjaxAppender("appender");
var consoleAppender=JL.createConsoleAppender('consoleAppender');
appender.setOptions({"url": "http://localhost:8083/api/log"
});
JL().setOptions({"requestId":"35F7446D-86F1-47FA-A9EC-547FFF510086","appenders": [appender]});

Thanks in advance

stringifyLogObject() : msg set to null cause exception

Hello,
In the function stringifyLogObject() when actualLogObject has a type of object, if actualLogObject is not an instance of RegExp, String, Number or Boolean, the function return a new StringifiedLogObject with the first param set to null.
This params correspond to the msg member of the class and in some case it cause exception break.

For example for winston.transport.email in the function log :

 var msgOptions = {
    from: this.from,
    to: this.to,
    subject: mustache.render(this.subject, {level: level, msg: msg.split('\n')[0]}),
    text: body,
  }

msg.split() cause an exception.
My question : "Is this this normal for the msg param to be set to null ?"
Best Regards.
Cyril

onunhandledrejection doesn't pass error to console

Issue

  • Based on MDN there is no info about return for onunhandledrejection
  • Probably because of this any exception from promise doesn't show within browser console! It looks dangerous because it might lead to confuse on debug assuming there is no error, but they just not showing

Solution

return should be removed from onunhandledrejection to allow browser handle the error and show it in the console.

Example custom appender

Hi,
First of all, I love JSNlog. I've been battling with a number of logging solutions for a JS client application, and none worked well, so thanks for creating this.

However, I'm stuck on something. I'm trying to write a custom appender which is basically a modification to the console appender. I keep hitting issues with the typescript definitions, probably because I'm pretty new to typescript.

Do you have an example appender template which we could use to create our own appenders - something that sits outside the JSNLog package, but references it correctly?

Regards,
Andy

Flushing Appender

Hello,

I was wondering if there was a built in method for flushing the log messages for a particular appender. I have a situation where I want to remove an appender, but I want to force it to send out its messages before I do that. I found that I can call sendLogItems directly to do this, but I feel like it's inappropriate to be calling a function like this that seems like it is more of an internal function. If I'm using the buffering I can just force a miscellaneous log of a message at the sendWithBufferLevel to push the messages out. However, if I'm doing the batching instead I don't see any obvious way. I know I can set the batchTimeout option (which I am doing currently) to have it periodically send, but I was hoping there would be a way to force it early.

XmlSerailizers not found

I get below error during my app build.
When logging I get jsnlog.logger 500 Internal Server Error.
The assembly with display name 'jsnlog.XmlSerializers' failed to load in the 'LoadFrom' binding context of the AppDomain with ID 2. The cause of the failure was: System.IO.FileNotFoundException: Could not load file or assembly 'jsnlog.XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=742e180f6c5ccd0d' or one of its dependencies. The system cannot find the file specified.

Browserify + jsnlog

I'm trying to use JSNLog with browserify, but whenever I bundle it in, something terrible happens.

this: var __extends = this.__extends ||

gets transformed into this: var __extends = undefined.__extends ||

Obviously theundefined.__extends is far from valid and thus throws errors. Removing this seems to solve the overall issue, but I'm not sure if that is an actual valid solution. I'm using browserify with reactify, and babelify.

Logging objects with cyclic values

If an object is being logged that contains cyclic references (to itself or to one of its (sub-)properties), you get "TypeError: cyclic object value" (see http://stackoverflow.com/a/9382383/99904).

I would suggest replacing return new StringifiedLogObject(null, actualLogObject, JSON.stringify(actualLogObject)); with return new StringifiedLogObject(null, actualLogObject, JSON.stringify(JSON.decycle(actualLogObject))); to avoid the JS error and actually log something.

Updated TypeDefinitions

Its appears the definitions on DefinitelyTyped are stale.

Is there a possibility to have these just included in the NPM package using the appropriate "typings" config: link?

Logging uglified logs

Hello,

  I am using JSNLogger in angular app having uglification & minification done. The Logs which are getting posted to server or the stacktrace posted to server is uglified.. how can we make it readable.

Thanks,
VP

Can't use jsnlog from ES6 client application

I've been struggling with how to import jsnlog in my Aurelia/ES6 application. Asked a question on SO also. One of the recommendations was to have a separate build output where typescript is set to output to ES6.

import 'jsnlog';            // JL is undefined
import JL from 'jsnlog';    // JL is {}
import {JL} from 'jsnlog';  // JL is undefined

Is this a possibility or is there something I'm missing (likely).

Use dir for objects in consoleAppender

Improve the consoleAppender so that when log item is an object, it:
For chrome, it passes the object (not a stringified version) to console.log (does same as dir, but bit more user friendly)
For Firefox, it passes it to console.dir. However, if user uses firebug, would be better to use console.log as well.
For IE, it uses the stringified version (its log and dir don't understand embedded json objects inside another json object)

Debug and Trace level is not logging in Console even if the level is set to Trace/Debug/All

In Angular 2 application, I have created two appenders and injected the JL as per the document.

app.module.ts

var ajaxAppender = JL.createAjaxAppender('ajaxAppender');
ajaxAppender.setOptions({
  "batchSize": 6,
  "bufferSize": 40,
})
var consoleAppender = JL.createConsoleAppender('consoleAppender');

JL().setOptions({
  level:1000,
  "appenders": [consoleAppender, ajaxAppender]
});

  providers: [
    { provide: 'JSNLOG', useValue: JL },
     AppService,
  ],

app.component.ts

constructor(@Inject('JSNLOG') JL: JL.JSNLog) {
    this.JL = JL;
}
ngOnInit() {
    this.JL().trace("It is a trace message");
    this.JL().debug("It is a debug message");
    this.JL().info("It is info message");
    this.JL().warn("It is a warn message");
    this.JL().error("It is a error message");
    this.JL().fatal("It is a fatal message");
  }

In the console, only info and above messages are showing. But not trace and debug.
AjaxAppender is showing trace and above as expected.

Ability to instrument the constructor and object functions

If you override the JavaScript function object, you can get them to

  1. check their own name, and if they have a given name:
  2. run within try ... catch, logging exceptions
  3. instrument all function objects in their prototype.

Not sure if this is possible.

Errors when running the provided jsnlog.js script through YUI Compressor.

Hello,

Using YUI Compressor (https://yui.github.io/yuicompressor/) 2.4.8 against the jsnlog.js file included in a clone of master at commit 96600bc results in a number of errors being reported:

$ java -jar yuicompressor-2.4.8.jar jsnlog.js
[ERROR] in jsnlog.js
  214:53:invalid property id
[ERROR] in jsnlog.js
  217:49:invalid property id
[ERROR] in jsnlog.js
  220:49:invalid property id
[ERROR] in jsnlog.js
  226:53:invalid property id
[ERROR] in jsnlog.js
  230:30:invalid property id
[ERROR] in jsnlog.js
  230:31:syntax error
[ERROR] in jsnlog.js
  234:47:invalid property id
[ERROR] in jsnlog.js
  309:58:missing name after . operator
[ERROR] in jsnlog.js
  695:62:missing name after . operator
[ERROR] in jsnlog.js
  697:40:missing ; before statement
[ERROR] in jsnlog.js
  698:28:syntax error
[ERROR] in jsnlog.js
  700:89:missing name after . operator
[ERROR] in jsnlog.js
  701:58:missing ; before statement
[ERROR] in jsnlog.js
  719:37:missing ) in parenthetical
[ERROR] in jsnlog.js
  719:38:syntax error
[ERROR] in jsnlog.js
  725:57:missing name after . operator
[ERROR] in jsnlog.js
  729:13:missing ) in parenthetical
[ERROR] in jsnlog.js
  731:19:invalid return
[ERROR] in jsnlog.js
  732:9:syntax error
[ERROR] in jsnlog.js
  755:15:invalid return
[ERROR] in jsnlog.js
  756:5:syntax error
[ERROR] in jsnlog.js
  789:1:syntax error
[ERROR] in jsnlog.js
  1:0:Compilation produced 22 syntax errors.
org.mozilla.javascript.EvaluatorException: Compilation produced 22 syntax errors.
    at com.yahoo.platform.yui.compressor.YUICompressor$1.runtimeError(YUICompressor.java:172)
    at org.mozilla.javascript.Parser.parse(Parser.java:396)
    at org.mozilla.javascript.Parser.parse(Parser.java:340)
    at com.yahoo.platform.yui.compressor.JavaScriptCompressor.parse(JavaScriptCompressor.java:315)
    at com.yahoo.platform.yui.compressor.JavaScriptCompressor.<init>(JavaScriptCompressor.java:536)
    at com.yahoo.platform.yui.compressor.YUICompressor.main(YUICompressor.java:147)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.yahoo.platform.yui.compressor.Bootstrap.main(Bootstrap.java:21)
$

It appears to be due to the use of "final" as a property identifier in a number of places.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar lists "final" as a future reserved keyword in some older ECMAScript standards.

Replacing the occurrences of "final" with some other identifier (for example, "final1") does allow YUI Compressor to process the script without reporting any errors.

(I did notice the jsnlog.min.js file that's provided, btw. Reporting this anyways, as it may cause problems when integrating the developer-friendly jsnlog.js file with existing projects that are already using YUI Compressor instead of Google Closure Compiler or some other tool.)

Cannot read property 'message' of undefined in `onunhandledrejection`

In the latest version of jsnlog with the new onunhandledrejection handler, I'm getting an error:

Uncaught TypeError: Cannot read property 'message' of undefined
at window.onunhandledrejection (jsnlog.js:829)

The error is here in the code and is caused b/c event.reason is undefined. Maybe it should be
"errorMsg": event.reason ? event.reason.message : null?

Thanks for the great library and all your hard work!

"TypeError: jsnlog_1.JL is not a function" with TypeScript and SystemJS

Hi.

Thank you for jsnlog.js.

I'm trying to integrate jsnlog.js using TypeScript and SystemJS, similar to issue #24, but it happens with JSNLog 2.25.1.

I've attached a sample Visual Studio solution here.

Basically, this causes the JavaScript run-time error TypeError: jsnlog_1.JL is not a function in chrome:

import { JL } from "jsnlog";

JL().debug("Hello world");

But I'm able to work-around this issue using:

declare var JL;
import "jsnlog";

JL().debug("Hello world");

But then I lose typing.

Any thoughts?

Thank you!

babel is causing some issues

I mentioned this originally in #18 when I incorrectly blamed browserify.

it seems babel is transforming this: var __extends = this.__extends ||

into this: var __extends = undefined.__extends ||

Obviously theundefined.__extends is far from valid and thus throws errors.

I have left a repro repo here: https://github.com/tparnell8/jsnlogReproStep you should be able to see it for yourself. I copied the js file from the nuget package...

Loading the library asynchronously

Hi,

Your library looks awesome!

I'd like to use it, but not have it block the initial rendering of the page, which is very important for user experience. Some other logging libraries, like loggly, handle that like this:

<script type="text/javascript" src="logglyScriptUrl.js" async></script>
<script>
  var _LTracker = _LTracker || [];
  _LTracker.push({ /* config settings here */ });
</script>

In other words, they load the script asynchronously (so it doesn't block rendering), but seed the _LTracker global with a blank array right away. That way, calls from user code to _LTracker.push (their logging API) fall back to Array.prototype.push before the library loads, without throwing an exception. Then, when the library loads, it looks if the _LTracker global array contains any messages and logs them properly; after that _LTracker is a genuine instance of the library. (Configuring the library is also done through an initial push().)

Is something like this possible with your library? Obviously, your library has a bigger API surface area than just .push(), but maybe something like this wouldn't be too hard to support?

Appender should have a timeout to send a non-full batch

Current behaviour:

var ajaxAppender=JL.createAjaxAppender('ajaxAppender');
ajaxAppender.setOptions({"batchSize": 3});
JL().setOptions({
    "appenders": [ajaxAppender]
});
JL().info("Unwrapping pizza");
JL().info("Turning on oven");
// No logs sent by Ajax yet, because 2 < 3
setTimeout(function() { JL().info("Putting pizza in oven") }, 20 * 60 * 1000);

This caught me out for a while. I guess I assumed batchSize was there to be tweaked for performance with high frequency logging, and the appender would automatically drain.

Proposed behaviour:

ajaxAppender.setOptions({"batchSize": 3, "batchPeriod": 1000});
JL().info("Unwrapping pizza");
JL().info("Turning on oven");
// 1000ms elapses, then 2 log messages are sent by Ajax
setTimeout(function() { JL().info("Putting pizza in oven") }, 20 * 60 * 1000);

I understand the behaviour of an implementation is debatable. Happy to work on some pull requests if this otherwise seems sane.

Is there a way to have <script src='jsnlog.min.js' /> before the initialization script

I use jsnlog in one of my ASP.NET MVC5 projects. I use the @Html.Raw(JSNLog.JavascriptionLogging.Configure()) at the top of my layout page. It keeps errorring during page load complaining about:

0x800a1391 - JavaScript runtime error: 'JL' is undefined

Script on HTML

<script type="text/javascript"> // </script> <script type="text/javascript" src="/Scripts/jsnlog.min.js"></script>

If I include the jsnlog.min.js at the top like below, it works but jsnlog.min.js will be loaded twice. Please advice. Thanks.

<script src="~/Scripts/jsnlog.min.js"></script>

@Html.Raw(JSNLog.JavascriptLogging.Configure())

Support for exceptions

On logger object, introduce a method
exception(msg, exception)

This adds a stack trace and logs message and exception, with severity fatal.

See if you can support inner exceptions.

Use built in stack trace functionality where possible. Otherwise just leave it for now. Keep it very short.

2.19.0 broken on Node.js: ReferenceError: window is not defined

Changes in 2.19.0 have broken jsnlog.js in Node.js. The check for window being defined raises a reference error in that environment: ReferenceError: window is not defined. The check should be typeof window !== 'undefined' similar to the checks elsewhere in the code.

AjaxAppender error handling

Hi Matt!

I'm using your jsnlog.js in my angular app. And it will be great to know when AjaxAppender can't send logs to server and why.

Here is your code:

try {
    // .......

    // Send the json to the server.
    // Note that there is no event handling here. If the send is not
    // successful, nothing can be done about it.

    var xhr = new XMLHttpRequest();
    xhr.open('POST', ajaxUrl);

    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('JSNLog-RequestId', JL.requestId);
    xhr.send(json);
} catch (e) { }

There is no error handling at all!
For this problem we can add ajaxErrorHandler function to appender (or appender's config), and call this function every time something goes wrong. Something like:

try{
    //...........
    var xhr = new XMLHttpRequest();
    xhr.open('POST', ajaxUrl, true); // async call is better

    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('JSNLog-RequestId', JL.requestId);

    xhr.onreadystatechange = function() {
        if (xhr.readyState != 4) return; // request is completed
        if (xhr.status != 200) {
            ajaxErrorHandler(xhr.status + ": " + xhr.statusText); // call our error handler
        }
    }

    xhr.send(json);

} catch (e) {
    ajaxErrorHandler("Fatal logger exception", e);
}

I wrote this code from my head and didn't test it. I just show the main idea.
Can you implement this feature please?

XMLHttpRequest is not defined

Yesterday I build an already running application and this error occurs on app.js on line
var JL = require('jsnlog').JL

Running the application with nodemon, it returns this error:


/home/osboxes/TCF/tcfWebServer/node_modules/jsnlog/jsnlog.js:91
    JL._createXMLHttpRequest = function () { return new XMLHttpRequest(); };
                                                        ^

ReferenceError: XMLHttpRequest is not defined
    at Function.JL._createXMLHttpRequest (/home/osboxes/TCF/tcfWebServer/node_modules/jsnlog/jsnlog.js:91:57)
    at new AjaxAppender (/home/osboxes/TCF/tcfWebServer/node_modules/jsnlog/jsnlog.js:601:28)
    at JL (/home/osboxes/TCF/tcfWebServer/node_modules/jsnlog/jsnlog.js:896:27)
    at Object.<anonymous> (/home/osboxes/TCF/tcfWebServer/node_modules/jsnlog/jsnlog.js:912:3)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/osboxes/TCF/tcfWebServer/app.js:21:27)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)

Anybody can help me, please?
Thanks in advance

Alby

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.