Skip to content

Commit

Permalink
feat: support query hook
Browse files Browse the repository at this point in the history
  • Loading branch information
ethanresnick committed Nov 26, 2022
1 parent 5e6f995 commit 5e50b92
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
isWrapped,
InstrumentationBase,
InstrumentationNodeModuleDefinition,
safeExecuteInTheMiddle,
} from '@opentelemetry/instrumentation';

import { context, diag, trace, Span, SpanStatusCode } from '@opentelemetry/api';
Expand Down Expand Up @@ -240,6 +241,33 @@ export class PgInstrumentation extends InstrumentationBase {
}
}

if (
typeof instrumentationConfig.queryHook === 'function' &&
queryConfig
) {
safeExecuteInTheMiddle(
() => {
instrumentationConfig.queryHook!(span, {
data: {
text: queryConfig.text,
// nb: the casts below are not type safe; they'll be wrong in
// the presence of illegal arguments. But we leave it up to
// the queryHook to handle that, and we catch and swallow any
// errors it throws.
values: queryConfig.values as unknown[],
name: queryConfig.name as string | undefined,
},
});
},
err => {
if (err) {
diag.error('Error running query hook', err);
}
},
true
);
}

let result: unknown;
try {
result = original.apply(this, args as never);
Expand Down
16 changes: 16 additions & 0 deletions plugins/node/opentelemetry-instrumentation-pg/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,28 @@ export interface PgInstrumentationExecutionResponseHook {
(span: api.Span, responseInfo: PgResponseHookInformation): void;
}

export interface PgQueryHookInformation {
data: pgTypes.QueryConfig;
}

export interface PgInstrumentationExecutionQueryHook {
(span: api.Span, queryInfo: PgQueryHookInformation): void;
}

export interface PgInstrumentationConfig extends InstrumentationConfig {
/**
* If true, additional information about query parameters will be attached (as `attributes`) to spans representing
*/
enhancedDatabaseReporting?: boolean;

/**
* Hook that allows adding custom span attributes or updating the
* span's name based on the data about the query to execute.
*
* @default undefined
*/
queryHook?: PgInstrumentationExecutionQueryHook;

/**
* Hook that allows adding custom span attributes based on the data
* returned from "query" Pg actions.
Expand Down

0 comments on commit 5e50b92

Please sign in to comment.