- 首先確定需要做的事情,生成用戶唯一的憑證(放在緩存中,同時(shí)兼容外部傳參)
/* uid生成方法 兼容的在初始化時(shí)處理 */
export function generateTmpUid () : string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
- 獲取當(dāng)前的環(huán)境信息,當(dāng)前的頁(yè)面地址(可用于統(tǒng)計(jì)pv/uv等)、屏幕寬高、用戶點(diǎn)擊事件(暫時(shí)不管、放在行為監(jiān)控一起),此處可以得到用戶點(diǎn)擊何處產(chǎn)生的異常
頁(yè)面標(biāo)題: document.title
來源頁(yè)面: document.referrer
當(dāng)前頁(yè)面: document.url
當(dāng)前語(yǔ)言: navigator.language
屏幕寬度: window.innerWidth
屏幕高度: window.innerHeight
下載網(wǎng)速: navigator.connection.downlink
網(wǎng)絡(luò)類型: navigator.connection.effectiveType
- 錯(cuò)誤監(jiān)聽方法,window.onerror + console重寫(同一需要兼容外部傳入異常信息,兼容vue、react等)
window.onerror = (message, source, line, column, error) => {
// 此處將 錯(cuò)誤信息封裝 拼接成 解析時(shí)所需要的格式 上報(bào)到服務(wù)器
let msg = ``
// 暫存到緩存中 根據(jù)項(xiàng)目流量選擇上報(bào)方式 前期可全部上報(bào) reportedDate(msg)
}
/* 定義錯(cuò)誤數(shù)據(jù) {type: 'error', message: 'xxxx'} */
console.error = (function (originalConsole) {
return function () {
if (arguments[0].hasOwnProperty('type')) {
reportedDate(arguments[0].message)
}
originalConsole(arguments[0])
}
})(console.error)
- 異常上報(bào)方法(異常上報(bào)方案)
/* 優(yōu)先sendBeacon, 沒有時(shí)再使用img src屬性 原因:性能問題 */
export function reportedDate (data: string) : void {
if (!navigator.sendBeacon) {
let img: any = new Image()
img.onload = img.onerror = function () {
img = null
}
img.src = `${data}`
} else {
navigator.sendBeacon('', data)
}
}
// 備注:上報(bào)方案在,完整的代碼中處理,按照異常數(shù)據(jù)類型,采用不同的上報(bào)方案,致命錯(cuò)誤類型上報(bào)到報(bào)警接口,非致命錯(cuò)誤上報(bào)到日志接口,等待事件處理
- nginx配置,shell腳本編寫(日志備份,刪除過期日志)
server {
listen 80;
server_name log.xxxx.com;
root /www/log.xxxx.com;
#charset koi8-r;
#access_log off;
location / {
return 404;
}
location = /log.gif {
default_type image/gif;
#access_log on;
access_log /log/log.xxxx.com/log.xxxx.com.log log.xxxx.com;
# 這種請(qǐng)求一般不緩存
add_header Expires "Fri, 01 Jan 1980 00:00:00 GMT";
add_header Pragma "no-cache";
add_header Cache-Control "no-cache, max-age=0, must-revalidate";
#echo 'hello log server';
# 一般獨(dú)立記錄日志的請(qǐng)求,都會(huì)返回一張 1×1 的空白gif圖
#empty_gif;
}
}
.sh 備份腳本
#!/bin/bash
base_path=/www/log/log.xxxx.com/ #日志文件目錄
log_name=log.xxxx.com.log #日志文件名
log_path_y=$(date -d yesterday '+%Y' )
log_path_md=$(date -d yesterday '+%m%d')
log_path_hms=$(date -d yesterday '+%H%M%S')
mv $base_path$log_name /www/log/backups/$log_path_md-$log_name #移動(dòng)日志
touch $base_path$log_name #生成新日志文件
kill -USR1 `cat /etc/nginx/log/nginx.pid` #nginx重讀配置文件
腳本啟動(dòng)命令
crontab -e
0 0 * * * sh /home/sh/runlog.sh
完整項(xiàng)目在完善好之后上傳到github