log + ajax, front-end logging solution.
lajax attempts to solve these problems:
There are no logs on the front end, or there are logs but no persistence, making it difficult to trace and analyze online problems;
Even if a front-end log library is used, it usually relies on developers to manually record logs, which is unreliable;
Uncaught exceptions in production environments are often ignored;
The mobile browser cannot see the logs printed by console
. In the past, alert
or vConsole was usually used to locate the problem, but the drawback is that the source code needs to be modified specifically for this purpose;
For web pages dynamically generated by the server, the system's original server logs cannot be correlated with the front-end logs.
Features
Online example
quick start
Api
Log format
request id
Server example
test
license
Manually record logs, supporting 3 log levels: info
, warn
, and error
;
The log will be printed in the browser console in an optimized format;
Automatically log uncaught script errors;
Automatically log uncaught Promise exceptions;
Automatically record the start and completion of ajax requests;
Automatically generate request IDs to facilitate log location and correlation;
Logs will be sent in batches to the configured log server regularly;
Good compatibility and exception handling mechanism.
http://eshengsky.github.io/lajax/
> npm install lajax
script
tag to introduce < script src =" ./dist/build.min.js " > </ script >
import Lajax from './src/lajax-module' ;
// 传入接口服务器地址进行实例化
const logger = new Lajax ( 'https://path/to/your/log/server' ) ;
// 记录一条信息日志
const num = parseInt ( Math . random ( ) * 100 ) ;
logger . info ( '这是一条info日志' , '会产生一个随机数:' , num ) ;
// 记录一条警告日志
logger . warn ( '这是一条警告日志!' ) ;
try {
JSON . parse ( undefined ) ;
} catch ( err ) {
// 记录一条错误日志
logger . error ( '这是一条error日志' , '捕获到一个错误:' , err ) ;
}
Please view the API for detailed documentation.
Lajax uses ES2015 syntax and needs to be packaged using webpack + babel.
> npm install
> webpack
The packaged file directory is ./dist
, where build.js
is the uncompressed version and build.min.js
is the compressed version.
Initialize the plug-in and return an instance of the plug-in.
Options
: string or object. If a string is passed in, it will be regarded as the log server address:
const logger = new Lajax ( 'https://path/to/your/log/server' ) ;
If you want to customize some configuration, please pass in an object:
const logger = new Lajax ( {
url : 'https://path/to/your/log/server' ,
interval : 5000
} ) ;
All properties supported by the object are as follows:
attribute name | illustrate | value type | default value |
---|---|---|---|
url | Log server URL | string | null |
autoLogError | Whether to automatically log uncaught errors | boolean | true |
autoLogRejection | Whether to automatically record Promise errors | boolean | true |
autoLogAjax | Whether to automatically record ajax requests | boolean | true |
logAjaxFilter | Ajax automatically records conditional filtering function. The function parameters are the URL and method of the request. If true is returned, it means logging, and false means no log is recorded. | function | /**
* @param {string} ajaxUrl - 请求url
* @param {string} ajaxMethod - 请求方式
*/
function ( ajaxUrl , ajaxMethod ) {
return true ;
} |
stylize | Whether to format the content printed by the console | boolean | true |
showDesc | Whether to display description information (printed on the console when initialization is completed) | boolean | true |
customDesc | A function that generates custom description information. The parameters passed are the number of unsent logs before the last page was unloaded, the current request id, whether the request id comes from the server, and a string is returned. | function | /**
* @param {number} lastUnsend - 上次页面卸载前未发送的日志数
* @param {string} reqId - 请求id
* @param {boolean} idFromServer - 请求id是否来自服务器
*/
function ( lastUnsend , reqId , idFromServer ) {
return ` lajax 前端日志模块加载完成。
自动记录页面错误: ${ this . autoLogError ? '✔' : '✘' }
自动记录Promise异常: ${ this . autoLogRejection ? '✔' : '✘' }
自动记录Ajax请求: ${ this . autoLogAjax ? '✔' : '✘' }
当前页面请求id: ${ reqId } ${ idFromServer
? ' (来自服务端)'
: ' (自动生成)' } ` ;
} |
interval | The interval between sending logs to the server (milliseconds) | number | 10000 |
maxErrorReq | The maximum number of consecutive errors when sending log requests. If this number is exceeded, the request will no longer be sent (but the request will still be recorded in the queue) | number | 5 |
Instance method records an information log and can pass in any type and any number of parameters.
const num = parseInt ( Math . random ( ) * 100 ) ;
logger . info ( '这是一条info日志' , '会产生一个随机数:' , num ) ;
Instance method, same as info
.
const num = parseInt ( Math . random ( ) * 100 ) ;
logger . log ( '这是一条log日志' , '会产生一个随机数:' , num ) ;
Instance method, records a warning log, and can pass in any type and any number of parameters.
logger . warn ( '这是一条警告日志!' ) ;
Instance method records an error log and can pass in any type and any number of parameters.
try {
JSON . parse ( undefined ) ;
} catch ( err ) {
// 记录一条错误日志
logger . error ( '这是一条error日志' , '捕获到一个错误:' , err ) ;
}
Array type attribute, the current log queue to be sent.
logger . queue
String type attribute, request id of the current page.
logger . reqId
boolean type attribute, whether the request id is generated by the server.
logger . idFromServer
Static object, enumeration of log colors. If you want to customize the log color, you can modify the properties of the object before calling the instance method. Default object:
Lajax . colorEnum = {
/**
* 信息日志颜色,默认宝蓝色
*/
info : 'DodgerBlue' ,
/**
* 警告日志颜色,默认橘黄色
*/
warn : 'orange' ,
/**
* 错误日志颜色,默认红色
*/
error : 'red' ,
/**
* ajax分组颜色,默认紫色
*/
ajaxGroup : '#800080' ,
/**
* 日志发送成功颜色,默认绿色
*/
sendSuccess : 'green' ,
/**
* 描述文字颜色,默认粉红色
*/
desc : '#d30775' ,
}
The log sent to the server through ajax must be a non-empty array. 2 logs are recorded here at the same time:
logger . info ( '这是一条info日志' , 'Hello' , 'lajax' ) ;
logger . warn ( '这是一条warn日志' ) ;
The actual log data sent will be as follows:
[{
"time" : " 2017-08-23 16:35:01.989 " ,
"level" : " info " ,
"messages" : [ " {44b53aba-1970-4bd1-b741-ed1ae5a5051e} " , "这是一条info日志" , " 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" : " 2017-08-23 16:35:02.369 " ,
"level" : " warn " ,
"messages" : [ " {44b53aba-1970-4bd1-b741-ed1ae5a5051e} " , "这是一条warn日志" ],
"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 "
}]
Description of each field:
time
: string, the time of the log record
level
: string, the level of the log, which is divided into three types: info
, warn
, and error
.
messages
: array. The first element of the array is the unique request ID wrapped in curly brackets. All subsequent elements correspond to the log content passed in by calling logger[level]
url
: string, the URL of the page where the log is located
agent
: string, the user agent of the page where the log is located
Each log sent to the server contains a request ID. In the same request, the request IDs of all logs must be the same; in different requests, the request IDs of the logs recorded must be different.
For example: When user A accessed index.html, lajax recorded and sent 10 logs, and the request IDs of these 10 logs were the same; User B also visited the page, and also generated 10 logs, and the request IDs of these logs were It must be the same, but different from user A's request id.
The main purpose of the request ID: allows you to accurately locate all related logs during a certain request on the server side.
Generation and sending of request id:
If your page is dynamically generated on the server side and you want to connect 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 successively try to find the request id from the <meta name="_reqId" content="xxxx-xxx">
content of the page or window._reqId
;
If the above search fails, your page is considered to be a pure front-end page. Lajax will generate a time-based unique ID as the request ID during initialization. Before the page is unloaded, all logs will contain this request. id;
For monitored ajax requests, the above request id will be added to the X-Request-Id
request header. You can record the request id in the server log for correlation.
In the ./demo
directory, a simple log server example server.js based on node.js is included.
Start the log server:
> node server.js
The log interface runs at http://127.0.0.1:2017/log. When testing locally, set the Lajax initialization parameters to this address:
const logger = new Lajax ( 'http://127.0.0.1:2017/log' ) ;
This sample server supports ajax cross-domain requests :)
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.