Skip to content
This repository was archived by the owner on Jan 21, 2026. It is now read-only.

Commit 4d3d54e

Browse files
authored
fix: rewrite all log messages (#700)
PR-URL: #700
1 parent 1fb53a7 commit 4d3d54e

4 files changed

Lines changed: 46 additions & 34 deletions

File tree

src/index.ts

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,9 @@ import * as traceUtil from './util';
3838

3939
export {Config, PluginTypes};
4040

41-
const modulesLoadedBeforeTrace: string[] = [];
42-
4341
const traceAgent = new TraceAgent('Custom Span API');
4442

43+
const modulesLoadedBeforeTrace: string[] = [];
4544
const traceModuleName = path.join('@google-cloud', 'trace-agent');
4645
for (let i = 0; i < filesLoadedBeforeTrace.length; i++) {
4746
const moduleName = traceUtil.packageNameFromPath(filesLoadedBeforeTrace[i]);
@@ -159,9 +158,12 @@ export function start(projectConfig?: Config): PluginTypes.TraceAgent {
159158

160159
if (modulesLoadedBeforeTrace.length > 0) {
161160
logger.error(
162-
'Tracing might not work as the following modules ' +
163-
'were loaded before the trace agent was initialized: ' +
164-
JSON.stringify(modulesLoadedBeforeTrace));
161+
'TraceAgent#start: Tracing might not work as the following modules',
162+
'were loaded before the trace agent was initialized:',
163+
`[${modulesLoadedBeforeTrace.sort().join(', ')}]`);
164+
// Stop storing these entries in memory
165+
filesLoadedBeforeTrace.length = 0;
166+
modulesLoadedBeforeTrace.length = 0;
165167
}
166168
// CLS namespace for context propagation
167169
cls.createNamespace();
@@ -177,7 +179,7 @@ export function start(projectConfig?: Config): PluginTypes.TraceAgent {
177179
if (typeof config.projectId !== 'string' &&
178180
typeof config.projectId !== 'undefined') {
179181
logger.error(
180-
'config.projectId, if provided, must be a string. ' +
182+
'TraceAgent#start: config.projectId, if provided, must be a string.',
181183
'Disabling trace agent.');
182184
stop();
183185
return traceAgent;
@@ -186,7 +188,7 @@ export function start(projectConfig?: Config): PluginTypes.TraceAgent {
186188
// Make trace agent available globally without requiring package
187189
global._google_trace_agent = traceAgent;
188190

189-
logger.info('trace agent activated');
191+
logger.info('TraceAgent#start: Trace Agent activated.');
190192
return traceAgent;
191193
}
192194

src/trace-api.ts

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,8 @@ export class TraceAgent implements TraceAgentInterface {
129129
// TODO validate options
130130
// Don't create a root span if we are already in a root span
131131
if (cls.getRootContext().type === SpanDataType.ROOT) {
132-
this.logger!.warn(this.pluginName + ': Cannot create nested root spans.');
132+
this.logger!.warn(`TraceApi#runInRootSpan: [${
133+
this.pluginName}] Cannot create nested root spans.`);
133134
return fn(UNCORRELATED_SPAN);
134135
}
135136

@@ -204,9 +205,10 @@ export class TraceAgent implements TraceAgentInterface {
204205
// with continuously growing number of child spans. The second case
205206
// seems to have some value, but isn't representable. The user probably
206207
// needs a custom outer span that encompasses the entirety of work.
207-
this.logger!.warn(
208-
this.pluginName + ': creating child for an already closed span',
209-
options.name, rootSpan.span.name);
208+
this.logger!.warn(`TraceApi#createChildspan: [${
209+
this.pluginName}] Creating phantom child span [${
210+
options.name}] because root span [${
211+
rootSpan.span.name}] was already closed.`);
210212
return UNCORRELATED_SPAN;
211213
}
212214
// Create a new child span and return it.
@@ -224,9 +226,9 @@ export class TraceAgent implements TraceAgentInterface {
224226
return UNTRACED_SPAN;
225227
} else {
226228
// Context was lost.
227-
this.logger!.warn(
228-
this.pluginName + ': Attempted to create child span ' +
229-
'without root');
229+
this.logger!.warn(`TraceApi#createChildspan: [${
230+
this.pluginName}] Creating phantom child span [${
231+
options.name}] because there is no root span.`);
230232
return UNCORRELATED_SPAN;
231233
}
232234
}

src/trace-writer.ts

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -90,9 +90,10 @@ export class TraceWriter extends common.Service {
9090

9191
if (onUncaughtExceptionValues.indexOf(config.onUncaughtException) === -1) {
9292
logger.error(
93-
'The value of onUncaughtException ' + config.onUncaughtException +
94-
' should be one of ',
95-
onUncaughtExceptionValues);
93+
`TraceWriter#constructor: The value of config.onUncaughtException [${
94+
config.onUncaughtException}] should be one of [${
95+
onUncaughtExceptionValues.join(', ')}].`,
96+
);
9697
// TODO(kjin): Either log an error or throw one, but not both
9798
throw new Error('Invalid value for onUncaughtException configuration.');
9899
}
@@ -123,9 +124,10 @@ export class TraceWriter extends common.Service {
123124
this.getProjectId((err: Error|null, project?: string) => {
124125
if (err) {
125126
this.logger.error(
126-
'Unable to acquire the project number from metadata ' +
127-
'service. Please provide a valid project number as an env. ' +
128-
'variable, or through config.projectId passed to start(). ' + err);
127+
'TraceWriter#initialize: Unable to acquire the project number',
128+
'automatically from the GCP metadata service. Please provide a',
129+
'valid project ID as environmental variable GCLOUD_PROJECT, or as',
130+
`config.projectId passed to start. Original error: ${err}`);
129131
cb(err);
130132
} else {
131133
this.config.projectId = project;
@@ -182,7 +184,9 @@ export class TraceWriter extends common.Service {
182184
.catch((err: AxiosError) => {
183185
if (err.code !== 'ENOTFOUND') {
184186
// We are running on GCP.
185-
this.logger.warn('Unable to retrieve GCE hostname.', err);
187+
this.logger.warn(
188+
'TraceWriter#getHostname: Unable to retrieve GCE hostname',
189+
`from the GCP metadata service. Original error: ${err}`);
186190
}
187191
cb(os.hostname());
188192
});
@@ -196,7 +200,9 @@ export class TraceWriter extends common.Service {
196200
.catch((err: AxiosError) => {
197201
if (err.code !== 'ENOTFOUND') {
198202
// We are running on GCP.
199-
this.logger.warn('Unable to retrieve GCE instance id.', err);
203+
this.logger.warn(
204+
'TraceWriter#getInstanceId: Unable to retrieve GCE instance ID',
205+
`from the GCP metadata service. Original error: ${err}`);
200206
}
201207
cb();
202208
});
@@ -256,18 +262,21 @@ export class TraceWriter extends common.Service {
256262
queueTrace(trace: Trace) {
257263
this.getProjectId((err, projectId?) => {
258264
if (err || !projectId) {
259-
this.logger.info('No project number, dropping trace.');
265+
this.logger.info(
266+
'TraceWriter#queueTrace: No project ID, dropping trace.');
260267
return; // if we even reach this point, disabling traces is already
261268
// imminent.
262269
}
263270

264271
trace.projectId = projectId;
265272
this.buffer.push(JSON.stringify(trace));
266-
this.logger.debug('queued trace. new size:', this.buffer.length);
273+
this.logger.info(
274+
`TraceWriter#queueTrace: buffer.size = ${this.buffer.length}`);
267275

268276
// Publish soon if the buffer is getting big
269277
if (this.buffer.length >= this.config.bufferSize) {
270-
this.logger.info('Flushing: trace buffer full');
278+
this.logger.info(
279+
'TraceWriter#queueTrace: Trace buffer full, flushing.');
271280
setImmediate(() => this.flushBuffer());
272281
}
273282
});
@@ -280,7 +289,7 @@ export class TraceWriter extends common.Service {
280289
* @private
281290
*/
282291
scheduleFlush() {
283-
this.logger.info('Flushing: performing periodic flush');
292+
this.logger.info('TraceWriter#scheduleFlush: Performing periodic flush.');
284293
this.flushBuffer();
285294

286295
// Do it again after delay
@@ -308,7 +317,7 @@ export class TraceWriter extends common.Service {
308317
// Privatize and clear the buffer.
309318
const buffer = this.buffer;
310319
this.buffer = [];
311-
this.logger.debug('Flushing traces', buffer);
320+
this.logger.debug('TraceWriter#flushBufffer: Flushing traces', buffer);
312321
this.publish(`{"traces":[${buffer.join()}]}`);
313322
}
314323

@@ -320,17 +329,16 @@ export class TraceWriter extends common.Service {
320329
publish(json: string) {
321330
const uri = `https://cloudtrace.googleapis.com/v1/projects/${
322331
this.config.projectId}/traces`;
323-
324332
const options = {method: 'PATCH', uri, body: json, headers};
325-
this.logger.debug('TraceWriter: publishing to ' + uri);
333+
this.logger.debug('TraceWriter#publish: Publishing to ' + uri);
326334
this.request(options, (err, body?, response?) => {
335+
const statusCode = (response && response.statusCode) || 'unknown';
327336
if (err) {
328-
this.logger.error(
329-
'TraceWriter: error: ',
330-
((response && response.statusCode) || '') + '\n' + err.stack);
337+
this.logger.error(`TraceWriter#publish: Received error status code ${
338+
statusCode}. Original error: ${err}`);
331339
} else {
332340
this.logger.info(
333-
'TraceWriter: published. statusCode: ' + response.statusCode);
341+
`TraceWriter#publish: Published w/ status code: ${statusCode}`);
334342
}
335343
});
336344
}

test/test-modules-loaded-before-agent.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ describe('modules loaded before agent', () => {
3939
trace.start();
4040
assert.strictEqual(
4141
logger.getNumLogsWith(
42-
'error', /modules.*loaded.*before.*trace agent.*: .*"shimmer"/),
42+
'error', /modules.*loaded.*before.*trace agent.*: .*shimmer/),
4343
1);
4444
});
4545
});

0 commit comments

Comments
 (0)