Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(tracing): Add db connection attributes for mysql spans #8775

Merged
merged 1 commit into from
Aug 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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