Log + Ajax, front-end log solution.
Lajax tries to address these issues:
-
There is no log in the front end, or there is no persistent log, which makes it difficult to trace and analyze online problems.
-
Even when front-end logging libraries are used, they often rely on manual logging by developers, which is unreliable.
-
Exceptions that are not caught in production are often ignored;
-
Mobile browsers cannot see logs printed by console. In the past, they used alert or vConsole to locate problems, but the defect was that they needed to modify the source code specifically for this purpose.
-
For web pages dynamically generated by the server, the original server logs of the system cannot be associated with front-end logs.
features
-
Manually record logs at info, WARN, and ERROR levels.
-
The logs are printed in an optimized format on the browser console;
-
Automatically log uncaught script errors;
-
Automatically logging uncaught Promise exceptions;
-
Automatically log the start and completion of ajax requests;
-
Automatically generate unique id based on request to facilitate log location;
-
Logs are periodically and in batches sent to the configured log server.
-
Good compatibility and exception handling mechanism.
eshengsky.github.io/lajax/
Quick start
- You can use
script
Tags introduced
<script src="./dist/build.min.js"></script>Copy the code
- You can also import ES2015 modules
import Lajax from './src/lajax-module';Copy the code
The basic use
//Pass in the interface server address for instantiation
const logger = new Lajax('https://path/to/your/log/server');
//Record an information log
const num = parseInt(Math.random(a)* 100);
logger.info('This is an INFO log'.'Generates a random number:', num);
//Log a warning log
logger.warn('This is a warning log!');
try {
JSON.parse(undefined);
} catch(err) {
//Log an error
logger.error('This is an error log'.'An error was caught:', err);
}Copy the code
See the Api for detailed documentation.
Lajax uses ES2015 syntax and currently needs to be packaged with Webpack before it can be used properly.
- Install the necessary modules
> npm installCopy the code
- Packaging plug-in
> webpackCopy the code
The packaged file directory is./dist, where build.js is the uncompressed version and build.min.js is the compressed version.
Api
Initialize the plug-in, returning an instance of the plug-in.
Options: string or object. If a string is passed in, it will be treated as the log server address:
const logger = new Lajax('https://path/to/your/log/server');Copy the code
If you want to customize some configuration, pass in an object:
const logger = new Lajax({
url: 'https://path/to/your/log/server',
interval: 5000
});Copy the code
All properties supported by the object are as follows:
The property name | instructions | Value types | The default value |
---|---|---|---|
url | URL of the log server | string | null |
autoLogError | Whether uncaught errors are automatically logged | boolean | true |
autoLogRejection | Whether Promise errors are automatically logged | boolean | true |
autoLogAjax | Whether ajax requests are automatically logged | boolean | true |
logAjaxFilter | Ajax automatically records the filtering criteria. Function parameters are the URL and method of the request. If true is returned, logs are logged, and false is not logged | function |
|
stylize | Whether to format the content printed by console | boolean | true |
showDesc | Display description (printed on console when initialization is complete) | boolean | true |
customDesc | User-defined description. The number of logs that were not sent last time, the id of the current request, and whether the request ID is from the server are returned as a string | function | – |
interval | Interval between logs being sent to the server (ms) | number | 10000 |
maxErrorReq | The maximum number of consecutive failed logging requests after which the request will not be sent (but will still be queued) | number | 5 |
info(arg1, arg2, … args)
Instance method, record an information log, can pass in any type, any number of parameters.
const num = parseInt(Math.random(a)* 100);
logger.info('This is an INFO log'.'Generates a random number:', num);Copy the code
Instance method, log a warning log, can pass in any type, any number of parameters.
logger.warn('This is a warning log!');Copy the code
error(arg1, arg2, … args)
Instance method, log an error log, can pass in any type, any number of parameters.
try {
JSON.parse(undefined);
} catch(err) {
//Log an error
logger.error('This is an error log'.'An error was caught:', err);
}Copy the code
Instance method to display the current log queue.
logger.info(logger.showQueue());Copy the code
colorEnum{… }
Static object, enumeration of log colors. If you want to customize log colors, you can modify the properties of this object before calling instance methods. Default object:
Lajax.colorEnum = {
/ * *
* Message log color, sapphire blue by default
* /
info: 'DodgerBlue'./ * *
* Warning log color, orange by default
* /
warn: 'orange'./ * *
Error log color, red by default
* /
error: 'red'./ * *
* Ajax group color, purple by default
* /
ajaxGroup: '# 800080'./ * *
* Color of sending logs successfully. The default color is green
* /
sendSuccess: 'green'./ * *
* Description text color, pink by default
* /
desc: '#d30775',}Copy the code
The log sent to the server via Ajax must be a non-empty array. Two logs are recorded simultaneously:
logger.info('This is an INFO log'.'Hello'.'lajax');
logger.warn('This is a WARN log');Copy the code
The actual log data sent is as follows:
[{
"time": "The 2017-08-23 16:35:01. 989"."level": "info"."messages": ["{44b53aba-1970-4bd1-b741-ed1ae5a5051e}"."This is an INFO log"."Hello"."lajax"]."url": "http://127.0.0.1:5500/demo/index.html"."agent": "Mozilla / 5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36"
}, {
"time": "The 2017-08-23 16:35:02. 369"."level": "warn"."messages": ["{44b53aba-1970-4bd1-b741-ed1ae5a5051e}"."This is a WARN log"]."url": "http://127.0.0.1:5500/demo/index.html"."agent": "Mozilla / 5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36"
}]Copy the code
Description of each field:
-
Time: indicates the time when the log is recorded
-
Level: indicates the log level. The value is a string of INFO, WARN, and error
-
Messages: an array in which the first element is the unique request ID wrapped in curly braces and all subsequent elements correspond to the contents of the log passed in by the call to Logger [level]
-
Url: indicates the URL of the page where the log is located
-
Agent: indicates the user agent of the page where the log resides
Request id
Each log sent to the server contains a request ID. In the same request, all logs must have the same request ID. In different requests, the request ID of the log must be different.
The main purpose of this request ID is to enable you to pinpoint all relevant logs for a particular request on the server side.
Request ID generation logic:
-
If your page is dynamically generated on the server side and you want to concatenate the server side logs with the front-end logs, you can generate a request ID on the server side and send it to the front-end. Lajax will try to find the request ID from
or from window._reqID in turn; -
If the above search fails, your page is considered a pure front-end page, and Lajax will generate a unique time-based ID as the request ID during initialization, which will be included in all logs before the page is unloaded.
In the./demo directory, there is a simple example log server server.js based on Node.js.
Start the log server:
> node server.jsCopy the code
Log interface running on http://127.0.0.1:2017/log, the local test, will Lajax initialization parameters can be set for the address:
const logger = new Lajax('http://127.0.0.1:2017/log');Copy the code
The sample server supports ajax cross-domain requests 🙂
test
Access the./test/index.html page locally to run the test.
The MIT License (MIT)
Copyright (c) 2017 Sun Zhenghua
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.