Skip to content

Instantly share code, notes, and snippets.

@kjin
Last active April 9, 2019 18:02
Show Gist options
  • Save kjin/8e07710b0684f5b4c9416bdc45b37fb6 to your computer and use it in GitHub Desktop.
Save kjin/8e07710b0684f5b4c9416bdc45b37fb6 to your computer and use it in GitHub Desktop.
Exports an object to set as Winston `defaultMeta` (do not use Object.assign to merge with other default metadata first)
let stackdriverLoggingWinston = null;
try {
stackdriverLoggingWinston = require('@google-cloud/logging-winston');
} catch (e) {}
const agent = global._google_trace_agent;
const enableThunkTimestamp = !!stackdriverLoggingWinston;
const enableThunkAgent = !!(stackdriverLoggingWinston
&& stackdriverLoggingWinston.LOGGING_TRACE_KEY
&& agent && agent.getCurrentContextId && agent.getWriterProjectId);
const defaultMeta = {};
if (enableThunkTimestamp) {
Object.defineProperty(defaultMeta, 'timestamp', {
enumerable: true,
get: () => new Date()
});
}
if (enableThunkAgent) {
const loggingTraceKey = stackdriverLoggingWinston.LOGGING_TRACE_KEY;
Object.defineProperty(defaultMeta, loggingTraceKey, {
enumerable: true,
get: () => {
const traceId = agent.getCurrentContextId();
if (!traceId) {
return null;
}
const traceProjectId = agent.getWriterProjectId();
if (!traceProjectId) {
return null;
}
return `projects/${traceProjectId}/traces/${traceId}`;
}
});
}
module.exports = defaultMeta;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment