大家好,我是小佑@小佐,是一名页面仔工程师,我会不定时在更新我的博客,有兴趣的可以点个关注来逛逛我的主页。 前言:日志是系统非常重要的东西,倘若生成环境中突然报错或异常,要想快速知道哪里出现了问题,最快的方式就是查看系统日志。日志不仅仅是系统异常后帮助定位错误的作用,也可以了解用户操作了什么请求,客户端ip和所在地址都是可以知道的,将用户的操作信息保存下来供系统管理员查看。下面来看看node是如何将日志信息保存下来并提供api给前端查看。
日志表结构
这是数据库的其中一张数据表,我将请求日志信息保存在这,方便管理员可以查看。
创建生成日志的中间件
//app.js
// 日志
app.use
(async
(ctx, next
) => {
let data
= ''
let params
= {}
if (ctx.method
== 'GET' || ctx.method
== 'get') {
data
= ctx.request.query
} else if (ctx.method
== 'POST' || ctx.method
== 'post') {
data
=ctx.request.body
}
//拦截入参做安全防护
await common.safety
((ctx.method
== 'GET' || ctx.method
== 'get') ? ctx.request.query
: (ctx.method
== 'POST' || ctx.method
== 'post') ? ctx.request.body
: {})
const start
= new Date
()
await next
()
const ms
= new Date
() - start
params.ms
= ms
params.ip
= await common.getClientIP
(ctx.req
)
let address
= (await common.getClientAddress
(params.ip
)).body
params.address
='局域网'
if (address.status
== 1
&&(address.province.length
||address.city.length
)) {
params.address
=address.province+address.city
}
params.url
= ctx.url
params.method
= ctx.method
params.params
= JSON.stringify
(data
)
let flag
= false
whiteList.noLogger.map
(res
=> {
if (ctx.url.indexOf
(res
) !== -1
) {
flag
= true
}
})
if (!flag
) {
await api.loggerData
(params
)
}
console.log
(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
这里面用到了安全性的问题,对入参数据进行校验;如:关键词、防脚本注入、防scrf等等。
//getClientIP方法
//获取用户的真实地址
async getClientIP
(req
) {
return (req.headers
['x-forwarded-for'] || // 判断是否有反向代理 IP
req.connection.remoteAddress
|| // 判断 connection 的远程 IP
req.socket.remoteAddress
|| // 判断后端的 socket 的 IP
req.connection.socket.remoteAddress
).replace
(/::ffff:/,
'')
}
这是用来获取客户端调api的ip地址。⚠️:局域网都是127.0.0.1
根据ip地址获取地理位置
//getClientAddress方法
//根据ip地址获取用户的地理位置
async getClientAddress
(ip
) {
let option
= {
method:
'get',
//
&key 不能写成?key
url:
`https://restapi.amap.com/v3/ip?parameters&key="您的key值"&ip=${ip}`
}
return await koa2Req
(option
)
}
根据ip地址获取客户端的地理位置是腾讯提供的第三方服务,不明白的可以看看=> IP定位
完成上述之后就可以将获取的数据插入日志表中了。
//api.js
//生成请求日志
loggerData: async
(params
) => {
let id = common.formatDateTime
(new Date
(),
'orderId')+Math.ceil
((Math.random() + 1) * 1000)
let nowtime = await common.formatDateTime(new Date())
let add_sql
= `insert into logger (id,ip,address,method,params,url,ms,createtime) values(${id},'${params.ip}','${params.address}','${params.method}','${params.params}','${params.url}','${params.ms}','${nowtime}')`
await allServices.query
(add_sql
)
}
至此就完成了系统日志的全部操作了。前端需要查看的时候就提供一个api获取表数据返回去就可以了。下一节将介绍前端人可以玩的定时任务。
上一篇:服务端图片上传与下载 下一篇:使用定时任务执行脚本