Skip to content

Instantly share code, notes, and snippets.

@svrnm
Created June 5, 2025 10:26
Show Gist options
  • Save svrnm/ea2a6e478e12f920d433066d9c0057ca to your computer and use it in GitHub Desktop.
Save svrnm/ea2a6e478e12f920d433066d9c0057ca to your computer and use it in GitHub Desktop.
native instrumentation vs instrumentation library
import { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';
import { trace, SpanStatusCode } from '@opentelemetry/api';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
export class MySimpleDbInstrumentation extends InstrumentationBase {
constructor() { super('mysimpledb', '1.0.0'); }
init() {
return [new InstrumentationNodeModuleDefinition('mysimpledb', ['*'], (mod) => {
this._wrap(mod, 'query', (orig) => async function (qStr) {
const q = mod.parse(qStr);
const span = trace.getTracer('mysimpledb', '1.0.0').startSpan('mysimpledb.query', {
attributes: {
[SemanticAttributes.DB_SYSTEM]: 'mysimpledb',
[SemanticAttributes.DB_OPERATION]: q.op,
[SemanticAttributes.DB_STATEMENT]: mod.buildQuery(q),
},
});
try {
return await orig.apply(this, [qStr]);
} catch (e) {
span.recordException(e);
span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });
throw e;
} finally {
span.end();
}
});
return mod;
}, (mod) => this._unwrap(mod, 'query'))];
}
}
const { trace, SpanStatusCode } = require('@opentelemetry/api');
const { SemanticAttributes } = require('@opentelemetry/semantic-conventions');
const tracer = trace.getTracer('mysimpledb', '1.0.0');
module.exports = {
query: async function (queryString) {
const query = parse(queryString);
return await tracer.startActiveSpan('mysimpledb.query', async (span) => {
span.setAttributes({
[SemanticAttributes.DB_SYSTEM]: 'mysimpledb',
[SemanticAttributes.DB_STATEMENT]: buildQuery(query),
[SemanticAttributes.DB_OPERATION]: query.op,
});
try {
if (query.op === 'INSERT')
return await write(query.table, query.columns, query.values);
if (query.op === 'SELECT')
return read(query.table, query.columns, query.where);
throw new OperationNotSupportedError(query.op);
} catch (err) {
span.recordException(err);
span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
throw err;
} finally {
span.end();
}
});
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment