Skip to content

Commit

Permalink
feat(tracing): Add db connection attributes for mysql spans (#8775)
Browse files Browse the repository at this point in the history
  • Loading branch information
AbhiPrasad committed Aug 10, 2023
1 parent fdd17e7 commit 8f5922d
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ test('should auto-instrument `mysql` package.', async () => {
op: 'db',
data: {
'db.system': 'mysql',
'db.user': 'root',
'server.address': expect.any(String),
'server.port': expect.any(Number),
},
},

Expand All @@ -22,6 +25,9 @@ test('should auto-instrument `mysql` package.', async () => {
op: 'db',
data: {
'db.system': 'mysql',
'db.user': 'root',
'server.address': expect.any(String),
'server.port': expect.any(Number),
},
},
],
Expand Down
36 changes: 36 additions & 0 deletions packages/tracing-internal/src/node/integrations/mysql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,18 @@ import type { LazyLoadedIntegration } from './lazy';
import { shouldDisableAutoInstrumentation } from './utils/node-utils';

interface MysqlConnection {
prototype: {
connect: () => void;
};
createQuery: () => void;
}

interface MysqlConnectionConfig {
host: string;
port: number;
user: string;
}

/** Tracing integration for node-mysql package */
export class Mysql implements LazyLoadedIntegration<MysqlConnection> {
/**
Expand Down Expand Up @@ -48,6 +57,32 @@ export class Mysql implements LazyLoadedIntegration<MysqlConnection> {
return;
}

let mySqlConfig: MysqlConnectionConfig | undefined = undefined;

try {
pkg.prototype.connect = new Proxy(pkg.prototype.connect, {
apply(wrappingTarget, thisArg: { config: MysqlConnectionConfig }, args) {
if (!mySqlConfig) {
mySqlConfig = thisArg.config;
}
return wrappingTarget.apply(thisArg, args);
},
});
} catch (e) {
__DEBUG_BUILD__ && logger.error('Mysql Integration was unable to instrument `mysql` config.');
}

function spanDataFromConfig(): Record<string, unknown> {
if (!mySqlConfig) {
return {};
}
return {
'server.address': mySqlConfig.host,
'server.port': mySqlConfig.port,
'db.user': mySqlConfig.user,
};
}

// The original function will have one of these signatures:
// function (callback) => void
// function (options, callback) => void
Expand All @@ -60,6 +95,7 @@ export class Mysql implements LazyLoadedIntegration<MysqlConnection> {
description: typeof options === 'string' ? options : (options as { sql: string }).sql,
op: 'db',
data: {
...spanDataFromConfig(),
'db.system': 'mysql',
},
});
Expand Down

0 comments on commit 8f5922d

Please sign in to comment.