|
| 1 | +const { Capi } = require('@tencent-sdk/capi') |
| 2 | +const logger = require('./logger') |
| 3 | +const { REUQEST_START_KEY } = require('./constants') |
| 4 | + |
| 5 | +// 字符串转16进制 |
| 6 | +function str2hex(str) { |
| 7 | + if (str === '') { |
| 8 | + return '' |
| 9 | + } |
| 10 | + const arr = [] |
| 11 | + for (let i = 0; i < str.length; i++) { |
| 12 | + arr.push(str.charCodeAt(i).toString(16)) |
| 13 | + } |
| 14 | + return arr.join('') |
| 15 | +} |
| 16 | + |
| 17 | +exports.reportHttp = async function(context, method, path, statusCode) { |
| 18 | + try { |
| 19 | + context = JSON.parse(decodeURIComponent(context)) |
| 20 | + path = str2hex(path) |
| 21 | + const ServiceType = 'monitor' |
| 22 | + const { |
| 23 | + tencentcloud_region, |
| 24 | + function_name: FunctionName, |
| 25 | + function_version: Version = '$latest', |
| 26 | + namespace: Namespace = 'default' |
| 27 | + } = context |
| 28 | + const environment = JSON.parse(context.environment || '{}') |
| 29 | + const { |
| 30 | + TENCENTCLOUD_SECRETID: SecretId, |
| 31 | + TENCENTCLOUD_SECRETKEY: SecretKey, |
| 32 | + TENCENTCLOUD_SESSIONTOKEN: Token, |
| 33 | + TENCENTCLOUD_REGION: envTencentRegion, |
| 34 | + REGION: envRegion |
| 35 | + } = environment |
| 36 | + const Region = tencentcloud_region || envTencentRegion || envRegion || 'ap-guangzhou' |
| 37 | + if (!SecretId || !SecretKey) { |
| 38 | + logger.warn('No SecretId or SecretKey in environment parameters.') |
| 39 | + return |
| 40 | + } |
| 41 | + const client = new Capi({ |
| 42 | + Region, |
| 43 | + SecretId, |
| 44 | + SecretKey, |
| 45 | + Token, |
| 46 | + ServiceType |
| 47 | + }) |
| 48 | + const commonParams = { |
| 49 | + Version: '2018-07-24', |
| 50 | + AnnounceInstance: `${Namespace}|${FunctionName}|${Version}` |
| 51 | + } |
| 52 | + const debugOptions = { |
| 53 | + debug: false, |
| 54 | + host: 'monitor.tencentcloudapi.com' |
| 55 | + } |
| 56 | + |
| 57 | + const latency = Date.now() - context[REUQEST_START_KEY] |
| 58 | + const keyPrefix = `${method}_${path}` |
| 59 | + const Metrics = [ |
| 60 | + { MetricName: 'request', Value: 1 }, |
| 61 | + { MetricName: keyPrefix, Value: 1 }, |
| 62 | + { MetricName: 'latency', Value: latency }, |
| 63 | + { MetricName: keyPrefix + '_latency', Value: latency }, |
| 64 | + { MetricName: keyPrefix + '_' + statusCode, Value: 1 } |
| 65 | + ] |
| 66 | + if (statusCode.startsWith('4')) { |
| 67 | + Metrics.push({ MetricName: '4xx', Value: 1 }) |
| 68 | + Metrics.push({ MetricName: 'error', Value: 1 }) |
| 69 | + } else if (statusCode.startsWith('5')) { |
| 70 | + Metrics.push({ MetricName: '5xx', Value: 1 }) |
| 71 | + Metrics.push({ MetricName: 'error', Value: 1 }) |
| 72 | + } |
| 73 | + |
| 74 | + return client.request( |
| 75 | + { |
| 76 | + Action: 'PutMonitorData', |
| 77 | + Metrics, |
| 78 | + ...commonParams |
| 79 | + }, |
| 80 | + debugOptions, |
| 81 | + true |
| 82 | + ) |
| 83 | + } catch (e) {} |
| 84 | +} |
0 commit comments