はじめに:ログはシステムで非常に重要です。実稼働環境で突然のエラーまたは例外が発生した場合、問題が発生した場所をすばやく知る最も速い方法は、システムログを表示することです。このログは、システムが異常になった後のエラーの特定に役立つだけでなく、ユーザーが操作した要求を理解するためにも使用されます。クライアントのIPとアドレスを知ることができ、ユーザーの操作情報はシステム管理者が表示できるように保存されます。ノードがログ情報を保存し、フロントエンド表示用のapiを提供する方法を見てみましょう。
ログテーブルの構造
これはデータベースのデータテーブルの1つです。管理者が表示できるように、ここにリクエストログ情報を保存します。
ログを生成するミドルウェアを作成する
//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アドレスを取得するために使用されます。⚠️:LANは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アドレスに基づいてクライアントの地理的位置を取得することは、Tencentが提供するサードパーティのサービスです。わからない場合は、=> 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を提供します。次のセクションでは、フロントエンドの人々がプレイできるタイミングタスクを紹介します。