@@ -35,6 +35,7 @@ import {
3535 resolveExceptionMessage ,
3636 resolveExceptionStacktrace ,
3737 resolveExceptionType ,
38+ resolveResponsePayload ,
3839 resolveResponseStatusCode ,
3940 resolveRpcStatusName ,
4041} from './errorUtil' ;
@@ -61,6 +62,22 @@ export interface LogPayload {
6162 'exception.stacktrace' ?: string ;
6263}
6364
65+ /**
66+ * Resolves a `LogSeverity` value across `google-logging-utils` versions where
67+ * `LogSeverity` may be exported as a type only.
68+ */
69+ function resolveLogSeverity (
70+ level : 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR' ,
71+ ) : loggingUtils . LogSeverity {
72+ return (
73+ (
74+ loggingUtils as {
75+ LogSeverity ?: Record < string , loggingUtils . LogSeverity > ;
76+ }
77+ ) . LogSeverity ?. [ level ] ?? ( level as loggingUtils . LogSeverity )
78+ ) ;
79+ }
80+
6481/**
6582 * Returns the `google-logging-utils` logger for the given GCP client service,
6683 * defaulting to the `'google-gax'` namespace when no service name is provided.
@@ -153,6 +170,48 @@ export function buildLogAttributes(
153170 return attributes ;
154171}
155172
173+ /**
174+ * Executes `fn` and attaches stream, promise, callback, or synchronous error
175+ * handlers to invoke `onError` when the operation fails.
176+ */
177+ function executeLoggedOperation < T > (
178+ fn : ( loggedCallback ?: APICallback ) => T ,
179+ onError : ( err : unknown ) => void ,
180+ isStreamCall : boolean ,
181+ userCallback ?: APICallback ,
182+ ) : T {
183+ // Wrap user callback to log RPC errors before forwarding.
184+ let callbackInvoked = false ;
185+ const loggedCallback : APICallback | undefined = userCallback
186+ ? function ( this : unknown , ...args : Parameters < APICallback > ) {
187+ callbackInvoked = true ;
188+ const err = args [ 0 ] ;
189+ if ( err ) {
190+ onError ( err ) ;
191+ }
192+ userCallback . apply ( this , args ) ;
193+ }
194+ : undefined ;
195+
196+ // Execute call and attach error handlers for streams, promises, or sync throws.
197+ try {
198+ const result = fn ( loggedCallback ) ;
199+ const promiseTarget = ! isStreamCall ? getPromiseTarget ( result ) : null ;
200+ if ( isStreamCall && result instanceof EventEmitter ) {
201+ handleStream ( result , onError , ( ) => { } , Boolean ( loggedCallback ) ) ;
202+ } else if ( promiseTarget ) {
203+ handlePromise ( promiseTarget , onError , ( ) => { } ) ;
204+ }
205+ return result ;
206+ } catch ( syncErr ) {
207+ // Avoid logging errors thrown inside userCallback after RPC completion.
208+ if ( ! callbackInvoked ) {
209+ onError ( syncErr ) ;
210+ }
211+ throw syncErr ;
212+ }
213+ }
214+
156215/**
157216 * Executes an API call and emits a single `WARNING` log entry if the logical
158217 * request fails across promise, callback, stream, or synchronous execution boundaries.
@@ -201,17 +260,10 @@ export function logCall<T = GaxCallResult>(
201260 // Build structured log attributes with exception details.
202261 const attributes = buildLogAttributes ( err , dynamicArgs , staticArgs ) ;
203262
204- const warningSeverity =
205- (
206- loggingUtils as {
207- LogSeverity ?: { WARNING : loggingUtils . LogSeverity } ;
208- }
209- ) . LogSeverity ?. WARNING ?? ( 'WARNING' as loggingUtils . LogSeverity ) ;
210-
211263 // Emit structured WARNING log.
212264 logger (
213265 {
214- severity : warningSeverity ,
266+ severity : resolveLogSeverity ( 'WARNING' ) ,
215267 ...( traceId ? { telemetryTraceId : traceId } : { } ) ,
216268 ...( spanId ? { telemetrySpanId : spanId } : { } ) ,
217269 other : attributes ,
@@ -221,34 +273,65 @@ export function logCall<T = GaxCallResult>(
221273 ) ;
222274 } ;
223275
224- // Wrap user callback to log RPC errors before forwarding.
225- let callbackInvoked = false ;
226- const loggedCallback : APICallback | undefined = userCallback
227- ? function ( this : unknown , ...args : Parameters < APICallback > ) {
228- callbackInvoked = true ;
229- const err = args [ 0 ] ;
230- if ( err ) {
231- emitL3WarnLog ( err ) ;
232- }
233- userCallback . apply ( this , args ) ;
234- }
235- : undefined ;
276+ return executeLoggedOperation ( fn , emitL3WarnLog , isStreamCall , userCallback ) ;
277+ }
236278
237- // Execute call and attach error handlers for streams, promises, or sync throws.
238- try {
239- const result = fn ( loggedCallback ) ;
240- const promiseTarget = ! isStreamCall ? getPromiseTarget ( result ) : null ;
241- if ( isStreamCall && result instanceof EventEmitter ) {
242- handleStream ( result , emitL3WarnLog , ( ) => { } , Boolean ( loggedCallback ) ) ;
243- } else if ( promiseTarget ) {
244- handlePromise ( promiseTarget , emitL3WarnLog , ( ) => { } ) ;
245- }
246- return result ;
247- } catch ( syncErr ) {
248- // Avoid logging errors thrown inside userCallback after RPC completion.
249- if ( ! callbackInvoked ) {
250- emitL3WarnLog ( syncErr ) ;
279+ /**
280+ * Executes an individual RPC transport attempt and emits a `DEBUG` log entry
281+ * if the attempt fails across promise, callback, stream, or synchronous execution boundaries.
282+ *
283+ * @template T
284+ * @param {AttemptTraceContext } attemptDynamicArgs - Dynamic context for the RPC attempt.
285+ * @param {StaticTraceContext } staticArgs - Static context for the client library.
286+ * @param {function } fn - The transport attempt operation to execute. Receives the wrapped
287+ * callback when `userCallback` is supplied, otherwise `undefined`.
288+ * @param {boolean } [isStreamCall=false] - Whether the operation returns a stream (`EventEmitter`).
289+ * @param {APICallback } [userCallback] - Optional attempt callback.
290+ * @returns {T } The return value of `fn`.
291+ */
292+ export function logNetworkAttempt < T = GaxCallResult > (
293+ attemptDynamicArgs : AttemptTraceContext ,
294+ staticArgs : StaticTraceContext ,
295+ fn : ( loggedCallback ?: APICallback ) => T ,
296+ isStreamCall = false ,
297+ userCallback ?: APICallback ,
298+ ) : T {
299+ // Snapshot attempt context in case async rejection loses active context.
300+ const initialContext = context . active ( ) ;
301+
302+ const emitL4DebugLog = ( err : unknown ) => {
303+ // Resolve logger and active T4 attempt span context for this attempt.
304+ const logger = getGaxLogger ( staticArgs ?. gcpClientService ) ;
305+ const attemptSpan =
306+ getActiveTraceContext ( ) ?. attemptSpan ??
307+ getActiveTraceContext ( initialContext ) ?. attemptSpan ;
308+ const spanContext = attemptSpan ?. spanContext ( ) ;
309+ const traceId = spanContext ?. traceId ;
310+ const spanId = spanContext ?. spanId ;
311+
312+ // Build structured log attributes and attach attempt metadata payload.
313+ const attributes = buildLogAttributes ( err , attemptDynamicArgs , staticArgs ) ;
314+ const responsePayload = resolveResponsePayload (
315+ ( err as { metadata ?: unknown } | null | undefined ) ?. metadata ,
316+ ) ;
317+ if ( responsePayload !== undefined ) {
318+ attributes [ 'response.payload' ] = responsePayload ;
251319 }
252- throw syncErr ;
253- }
320+
321+ // Emit structured DEBUG log for the failed attempt.
322+ const message = resolveExceptionMessage ( err , attemptDynamicArgs . rpcType ) ;
323+ logger (
324+ {
325+ severity : resolveLogSeverity ( 'DEBUG' ) ,
326+ ...( traceId ? { telemetryTraceId : traceId } : { } ) ,
327+ ...( spanId ? { telemetrySpanId : spanId } : { } ) ,
328+ other : attributes ,
329+ } ,
330+ 'RPC attempt failed: %s' ,
331+ message || err ,
332+ ) ;
333+ } ;
334+
335+ // Intercept and dispatch execution boundaries for the attempt.
336+ return executeLoggedOperation ( fn , emitL4DebugLog , isStreamCall , userCallback ) ;
254337}
0 commit comments