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: add custom logging #122

Merged
merged 1 commit into from
Sep 24, 2024
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
2 changes: 2 additions & 0 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ export class RDSClient extends Operator {
connection,
} as ConnectionMessage);
});
this.logging = options.logging;
}

async query<T = any>(sql: string, values?: object | any[]): Promise<T> {
Expand Down Expand Up @@ -162,6 +163,7 @@ export class RDSClient extends Operator {
try {
const _conn = await this.getConnectionWithTimeout();
const conn = new RDSConnection(_conn);
conn.setLogging(this.logging);
if (this.beforeQueryHandlers.length > 0) {
for (const handler of this.beforeQueryHandlers) {
conn.beforeQuery(handler);
Expand Down
10 changes: 10 additions & 0 deletions src/operator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
SelectOption,
UpdateOption, UpdateResult, UpdateRow,
PoolConnectionPromisify,
Logging,
} from './types';
import channels from './channels';
import type { QueryStartMessage, QueryEndMessage } from './channels';
Expand All @@ -20,6 +21,8 @@ const debug = debuglog('ali-rds:operator');
*/
export abstract class Operator {
#connection: PoolConnectionPromisify;
logging?: Logging;

constructor(connection?: PoolConnectionPromisify) {
if (connection) {
this.#connection = connection;
Expand All @@ -43,6 +46,10 @@ export abstract class Operator {
this.afterQueryHandlers.push(afterQueryHandler);
}

setLogging(logging?: Logging) {
this.logging = logging;
}

escape(value: any, stringifyObjects?: boolean, timeZone?: string): string {
return SqlString.escape(value, stringifyObjects, timeZone);
}
Expand Down Expand Up @@ -80,6 +87,9 @@ export abstract class Operator {
}
}
debug('[connection#%s] query %o', this.threadId, sql);
if (typeof this.logging === 'function') {
this.logging(sql, { threadId: this.threadId });
}
const queryStart = performance.now();
let rows: any;
let lastError: Error | undefined;
Expand Down
3 changes: 3 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export interface RDSClientOptions extends PoolConfig {
connectionStorage?: AsyncLocalStorage<Record<PropertyKey, RDSTransaction>>;
getConnectionConfig?: GetConnectionConfig;
poolWaitTimeout?: number;
logging?: Logging;
}

export interface PoolConnectionPromisify extends Omit<PoolConnection, 'query'> {
Expand Down Expand Up @@ -67,3 +68,5 @@ export type AfterQueryHandler = (sql: string, result: any, execDuration: number,

export type TransactionContext = Record<PropertyKey, RDSTransaction | null>;
export type TransactionScope = (transaction: RDSTransaction) => Promise<any>;

export type Logging = (message: string, ...args: any[]) => any;
24 changes: 24 additions & 0 deletions test/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,30 @@ describe('test/client.test.ts', () => {
});
});

describe('logging', () => {
const mockLogs: string[] = [];

it('should logging sql', async () => {
const db = new RDSClient({
...config,
logging: (sql, { threadId }) => {
assert(typeof threadId === 'number');
mockLogs.push(sql);
},
});

await db.query('show tables');
assert.deepEqual(mockLogs, [ 'show tables' ]);
// logging SQL string with variable replaced
await db.query('select * from ?? where email = ? limit 1',
[ table, prefix + '[email protected]' ]);
assert.deepEqual(mockLogs, [
'show tables',
`select * from \`${table}\` where email = '${prefix + '[email protected]'}' limit 1`,
]);
});
});

describe('beginTransactionScope(scope)', () => {
it('should beginTransactionScope() error', async () => {
const failDB = new RDSClient({
Expand Down
Loading