Skip to content

Commit

Permalink
format
Browse files Browse the repository at this point in the history
  • Loading branch information
sonnht-chotot committed Jun 17, 2021
1 parent b573c10 commit 1cce4a3
Show file tree
Hide file tree
Showing 8 changed files with 523 additions and 486 deletions.
7 changes: 4 additions & 3 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@
"SharedArrayBuffer": "readonly"
},
"parserOptions": {
"ecmaVersion": 2018
"ecmaVersion": 2020
},
"rules": {
"semi": "off",
"indent": ["warn", 2],
"quotes": ["warn", "double"],
"quotes": ["warn", "single"],
"no-console": "warn",
"space-before-function-paren": "off"
"space-before-function-paren": "off",
"camelcase":"off"
}
}
2 changes: 1 addition & 1 deletion context.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const asyncHooks = require("async_hooks");
const asyncHooks = require('async_hooks');
const contexts = {};
asyncHooks
.createHook({
Expand Down
6 changes: 3 additions & 3 deletions helper.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use strict";
'use strict';

const sensitive_keys = ['password', 'passwd', 'pwd', 'secret', 'token',
'card', 'authorization','pw', 'pass']
'card', 'authorization','pw', 'pass']

const tagPrimitive = (span, key, value) => {
span.setTag(key, value);
Expand Down Expand Up @@ -45,7 +45,7 @@ const isArray = input => {

const isExcludedPath = (method,requestPath, options) => {
const { excludedPath = [] } = options;
if (requestPath.includes("health") || requestPath.includes("public")) return true;
if (requestPath.includes('health') || requestPath.includes('public')) return true;
for (let index = 0; index < excludedPath.length; index++) {
const path = excludedPath[index];
if(requestPath.includes(path.url) && path.method.toLowerCase()===method.toLowerCase()) return true;
Expand Down
30 changes: 15 additions & 15 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { stringify } = require("flatted/cjs");
const { FORMAT_HTTP_HEADERS, FORMAT_TEXT_MAP } = require("opentracing");
const { tagObject, isExcludedPath } = require("./helper");
const { getContext, setContext } = require("./context");
const { stringify } = require('flatted/cjs');
const { FORMAT_HTTP_HEADERS, FORMAT_TEXT_MAP } = require('opentracing');
const { tagObject, isExcludedPath } = require('./helper');
const { getContext, setContext } = require('./context');
const {registration,signUpEvent} = require('./instruments')

const buildSpanName = req => {
Expand All @@ -20,10 +20,10 @@ const buildSpanName = req => {
return baseSpanName;
};

process.on("unhandledRejection", error => {
const errorSpan = globalTracer.startSpan("unhandledRejection");
errorSpan.setTag("error", true);
errorSpan.setTag("http.status_code", error.statusCode || 500);
process.on('unhandledRejection', error => {
const errorSpan = global.tracer.startSpan('unhandledRejection');
errorSpan.setTag('error', true);
errorSpan.setTag('http.status_code', error.statusCode || 500);
errorSpan.log({
error: JSON.stringify(error)
});
Expand Down Expand Up @@ -61,8 +61,8 @@ class JaegerMiddleware {
// let spanName = buildSpanName(req);
const span = parentSpan
? this._jaeger.startSpan(`${req.originalUrl}`, {
childOf: parentSpan
})
childOf: parentSpan
})
: this._jaeger.startSpan(`${req.originalUrl}`);
req.span = span;
setContext(span);
Expand Down Expand Up @@ -98,16 +98,16 @@ class JaegerMiddleware {
const parentSpan = this._jaeger.extract(FORMAT_TEXT_MAP, headers);
const span = parentSpan
? this._jaeger.startSpan(spanName, {
childOf: parentSpan
})
childOf: parentSpan
})
: this._jaeger.startSpan(spanName);
const spanContext = span;
tagObject(span,data)
setContext(spanContext);
return span;
}

spawnNewSpanWithData(spanName = "children-span",data={}) {
spawnNewSpanWithData(spanName = 'children-span',data={}) {
const context = getContext()
const newSpan = !isEmpty(context) ? this._jaeger.startSpan(spanName, {
childOf: context
Expand Down Expand Up @@ -167,7 +167,7 @@ class JaegerMiddleware {
try {
const span = req.span
if (res.statusCode !== 200) {
span.setTag("error", true);
span.setTag('error', true);
}
tagObject(span, req.query);
tagObject(span, req.params);
Expand All @@ -182,7 +182,7 @@ class JaegerMiddleware {
const info = {
timestamp: Date.now(),
request: JSON.stringify(requestInfo),
"response.body": stringify(res.resBody)
'response.body': stringify(res.resBody)
};
span.log(info);
} catch (error) {
Expand Down
44 changes: 22 additions & 22 deletions instruments.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,37 +5,37 @@ const emitter = require('./emitter')

log4js.levels = process.env.LOG_LEVEL || 'info'
const logger = log4js.getLogger('jaeger-client-nodejs-instruments')
const modules = ["mongodb"]
const modules = ['mongodb']



const registration = ()=>{
for (const module of modules) {
try {
require(`./instruments_modules/${module}`).start()
} catch (error) {
logger.info(`db module ${module} not found`)
}
for (const module of modules) {
try {
require(`./instruments_modules/${module}`).start()
} catch (error) {
logger.info(`db module ${module} not found`)
}
}
}

const signUpEvent = span =>{
for (const module of modules) {
emitter.on(module,(...agrs)=>{
const eventData = agrs[0]
const {db_type,operation_name,data}=eventData
const child_span = global.tracer.startSpan(operation_name,{
childOf: span
})
child_span.setTag("db_type",db_type)
helper.tagObject(child_span,data)
child_span.log(data)
child_span.finish()
})
}
for (const module of modules) {
emitter.on(module,(...agrs)=>{
const eventData = agrs[0]
const {db_type,operation_name,data}=eventData
const child_span = global.tracer.startSpan(operation_name,{
childOf: span
})
child_span.setTag('db_type',db_type)
helper.tagObject(child_span,data)
child_span.log(data)
child_span.finish()
})
}
}

module.exports = {
registration,
signUpEvent
registration,
signUpEvent
}
136 changes: 68 additions & 68 deletions instruments_modules/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,82 +4,82 @@ const emitter = require('../emitter')
const requestIdMap = {}

const onStart = (event) => {
// {
// address: '10.60.3.8:27017',
// connectionId: 2,
// requestId: 5,
// databaseName: 'user_profiler',
// commandName: 'createIndexes',
// command: {
// createIndexes: 'reasons',
// indexes: [ [Object] ],
// lsid: { id: [Binary] },
// '$db': 'user_profiler'
// }
// }
const {
databaseName,
commandName,
command,
requestId
} = event;
const {
filter = {},
projection = {},
// {
// address: '10.60.3.8:27017',
// connectionId: 2,
// requestId: 5,
// databaseName: 'user_profiler',
// commandName: 'createIndexes',
// command: {
// createIndexes: 'reasons',
// indexes: [ [Object] ],
// lsid: { id: [Binary] },
// '$db': 'user_profiler'
// }
// }
const {
databaseName,
commandName,
command,
requestId
} = event;
const {
filter = {},
projection = {},
limit,
query = {}
} = command
const collection = command[commandName]
const operation_name = `${databaseName}.${collection}.${commandName}`
// set operation name
requestIdMap[requestId] = `${databaseName}.${collection}.${commandName}`
if (!operation_name.includes('Index')) {
emitter.emit('mongodb', {
db_type: 'mongodb',
operation_name,
data: {
filter,
projection,
limit,
query = {}
} = command
const collection = command[commandName]
const operation_name = `${databaseName}.${collection}.${commandName}`
// set operation name
requestIdMap[requestId] = `${databaseName}.${collection}.${commandName}`
if (!operation_name.includes('Index')) {
emitter.emit('mongodb', {
db_type: 'mongodb',
operation_name,
data: {
filter,
projection,
limit,
query,
}
})
}
query,
}
})
}
}

const onEnd = (event) => {
const {
requestId,
reply = {},
duration = 0
} = event;
const {
cursor = {},
value = {}
} = reply
const operation_name = requestIdMap[requestId] + `_response`
const firstBatch = cursor ?.firstBatch || []
if (!operation_name.includes('Index')) {
emitter.emit('mongodb', {
db_type: 'mongodb',
operation_name,
data: {
command_duration_ms: duration,
write_operation_response: value,
read_operation_response: firstBatch
}
})
}
delete requestIdMap[requestId]
const {
requestId,
reply = {},
duration = 0
} = event;
const {
cursor = {},
value = {}
} = reply
const operation_name = requestIdMap[requestId] + '_response'
const firstBatch = cursor ?.firstBatch || []
if (!operation_name.includes('Index')) {
emitter.emit('mongodb', {
db_type: 'mongodb',
operation_name,
data: {
command_duration_ms: duration,
write_operation_response: value,
read_operation_response: firstBatch
}
})
}
delete requestIdMap[requestId]
}

const start = () => {
const path = process.cwd()
const listener = require(path + '/node_modules/mongodb').instrument()
listener.on("started", onStart)
listener.on("succeeded", onEnd)
const path = process.cwd()
const listener = require(path + '/node_modules/mongodb').instrument()
listener.on('started', onStart)
listener.on('succeeded', onEnd)
}

module.exports = {
start
start
}
Loading

0 comments on commit 1cce4a3

Please sign in to comment.