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

chore: add logger at integration level #3401

Merged
merged 42 commits into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
b982cb4
chore: add logging capability at integration level
May 21, 2024
37b4f47
chore: add structured logger in klaviyo
May 22, 2024
445ce1f
chore: add structured logger to src transform & proxyV1 integrations
May 22, 2024
5bbb38e
chore: add logging to gaec
May 27, 2024
0b7bfec
chore: add structured logger to transformer logger & use it for gaec …
May 27, 2024
65b6146
chore: structured logger referred from transformer logger refactor
May 27, 2024
e533b88
chore: response logging in garl
May 27, 2024
2939647
chore: add support for request logging in logger & gaec handler
May 27, 2024
734f900
chore: merge context & metadata for default notifier into a single ob…
May 27, 2024
8a6bf3a
chore: update response log message & responseDetails
May 27, 2024
4fc6c07
chore: add log to trck the request for offline conversion creation fo…
ItsSudip Jun 4, 2024
8ad1a5f
chore: update loglevel to warn for request and response logs
ItsSudip Jun 4, 2024
2d19625
chore: refactor with different convention of log levels
Jun 10, 2024
827157b
chore: set appropriate level for metalogger in benchmarking
Jun 11, 2024
12a4ce2
chore: load env in logger and fix logLevel condition logic
ItsSudip Jun 12, 2024
efdb9c5
chore: add request logs for google adwords destinations
Jun 12, 2024
365f738
chore: call env load before importing logger
Jun 12, 2024
cc43744
chore: upgrade integrations-lib
Jun 13, 2024
ab27fb7
Merge remote-tracking branch 'origin/develop' into chore.logging
Jun 13, 2024
00dd83b
chore: remove old references of logger
Jun 13, 2024
0f9558d
chore: refactor fire http stats
Jun 13, 2024
883f3cb
chore: add logic to trigger stats for destinations that don't send me…
Jun 13, 2024
1c4a1b0
chore: issues with func args fixed
Jun 13, 2024
c7cc39f
chore: debug-1
Jun 13, 2024
addae95
chore: debug-2
Jun 13, 2024
e1434c9
chore: debug-3
Jun 13, 2024
567c3b3
chore: fix levels problem
Jun 13, 2024
db31a6a
Merge remote-tracking branch 'origin/develop' into chore.logging
Jun 13, 2024
fd36803
Merge remote-tracking branch 'origin/develop' into chore.logging
Jun 14, 2024
a8b0c83
chore: add comment on LOGGER_IMPL
Jun 14, 2024
1e1f87e
chore: revert error log to info
Jun 14, 2024
fe87faa
chore: remove redundant condition on network.js
ItsSudip Jun 14, 2024
cbb9354
chore: update debug level condition
Jun 14, 2024
451fd11
chore: correction in shopify test
Jun 14, 2024
ed7837a
chore: usage of logger in postTransformation
Jun 14, 2024
0f9dc73
Merge remote-tracking branch 'origin/develop' into chore.logging
Jun 14, 2024
a978abf
chore: accept destType key from destinationType in metadata
Jun 14, 2024
710746f
chore: correction log message
Jun 14, 2024
6279c79
chore: add method doc for unexported log method in logger.js
Jun 14, 2024
4adb977
chore: handle non-object arguments for logger
Jun 18, 2024
2406a4b
chore: remove new routes log
Jun 18, 2024
d5b2282
Merge remote-tracking branch 'origin/develop' into chore.logging
Jun 18, 2024
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
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@
"@ndhoule/extend": "^2.0.0",
"@pyroscope/nodejs": "^0.2.9",
"@rudderstack/integrations-lib": "^0.2.10",
"@rudderstack/json-template-engine": "^0.13.0",
"@rudderstack/workflow-engine": "^0.8.1",
"@rudderstack/json-template-engine": "^0.13.2",
"@rudderstack/workflow-engine": "^0.8.2",
"@shopify/jest-koa-mocks": "^5.1.1",
"ajv": "^8.12.0",
"ajv-draft-04": "^1.0.0",
Expand Down
2 changes: 1 addition & 1 deletion src/adapters/network.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ const fireHTTPStats = (clientResponse, startTime, statTags) => {
startTime,
clientResponse,
};
if (statTags?.metadata && !Array.isArray(statTags?.metadata)) {
if (statTags?.metadata) {
const metadata = !Array.isArray(statTags?.metadata) ? [statTags.metadata] : statTags.metadata;
metadata?.forEach((m) => {
fireOutgoingReqStats({
Expand Down
3 changes: 2 additions & 1 deletion src/cdk/v2/destinations/gladly/procWorkflow.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ steps:
headers: $.getHeaders(.destination)
}
const endpoint = $.getEndpoint(.destination) + "?" + $.getQueryParams($.context.payload);
const rawResponse = await $.httpGET(endpoint,requestOptions)
const reqStats = {metadata:.metadata, module: 'router',feature: "transformation", destType:"gladly",requestMethod:"get",endpointPath:"/api/v1/customer-profiles"}
const rawResponse = await $.httpGET(endpoint,requestOptions, reqStats)
const processedResponse = $.processAxiosResponse(rawResponse)
processedResponse

Expand Down
3 changes: 2 additions & 1 deletion src/cdk/v2/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@ export async function processCdkV2Workflow(
bindings: Record<string, FixMe> = {},
) {
krishna2020 marked this conversation as resolved.
Show resolved Hide resolved
try {
logger.debug(`Processing cdkV2 workflow`);
logger.debug(`Processing cdkV2 workflow`, { destType });

const workflowEngine = await getCachedWorkflowEngine(destType, feature, bindings);
return await executeWorkflow(workflowEngine, parsedEvent, requestMetadata);
} catch (error) {
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ app.use(
addRequestSizeMiddleware(app);
addSwaggerRoutes(app);

logger.error('Using new routes');
logger.info('Using new routes');
sanpj2292 marked this conversation as resolved.
Show resolved Hide resolved
applicationRoutes(app);

function finalFunction() {
Expand Down
59 changes: 50 additions & 9 deletions src/logger.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,32 @@
const dotenv = require('dotenv');

/* istanbul ignore file */
const { LOGLEVELS, structuredLogger } = require('@rudderstack/integrations-lib');

// any value greater than levelError will work as levelNone
// LOGGER_IMPL can be `console` or `winston`
const loggerImpl = process.env.LOGGER_IMPL ?? 'winston';

krishna2020 marked this conversation as resolved.
Show resolved Hide resolved
let logLevel = process.env.LOG_LEVEL ?? 'error';

const logger = structuredLogger({ level: logLevel });
const logger = structuredLogger({
level: logLevel,
fillExcept: [
'destinationId',
'sourceId',
'destinationType',
'workspaceId',
'module',
'implementation',
'feature',
'destType',
],
});

const getLogger = () => {
return loggerImpl === 'winston' ? logger : console;
switch (loggerImpl) {
case 'winston':
return logger;
case 'console':
return console;
}
};

const setLogLevel = (level) => {
Expand All @@ -31,19 +46,45 @@ const getLogMetadata = (metadata) => {
if (Array.isArray(metadata)) {
[reqMeta] = metadata;
}
const destType = reqMeta?.destType || reqMeta?.destinationType;
return {
...(reqMeta?.destinationId && { destinationId: reqMeta.destinationId }),
...(reqMeta?.sourceId && { sourceId: reqMeta.sourceId }),
...(reqMeta?.workspaceId && { workspaceId: reqMeta.workspaceId }),
...(reqMeta?.destType && { destType: reqMeta.destType }),
...(destType && { destType }),
...(reqMeta?.module && { module: reqMeta.module }),
...(reqMeta?.implementation && { implementation: reqMeta.implementation }),
...(reqMeta?.feature && { feature: reqMeta.feature }),
};
};

const log = (logMethod, args) => {
const [message, logInfo, ...otherArgs] = args;
const formLogArgs = (args) => {
let msg = '';
let otherArgs = [];
args.forEach((arg) => {
if (typeof arg !== 'object') {
msg += ' ' + arg;
return;
}
otherArgs.push(arg);
});
return [msg, ...otherArgs];
};

/**
* Perform logging operation on logMethod passed
*
* **Good practices**:
* - Do not have more than one array args in logger
* @param {*} logMethod
* - instance method reference
* - The logger should implement all of debug/info/warn/error methods
* @param {*} logArgs
* - the arguments that needs to be passed to logger instance method
*/
const log = (logMethod, logArgs) => {
const [message, ...args] = formLogArgs(logArgs);
const [logInfo, ...otherArgs] = args;
if (logInfo) {
const { metadata, ...otherLogInfoArgs } = logInfo;
if (Array.isArray(metadata)) {
Expand Down Expand Up @@ -74,7 +115,7 @@ const log = (logMethod, args) => {

const debug = (...args) => {
krishna2020 marked this conversation as resolved.
Show resolved Hide resolved
const logger = getLogger();
if (LOGLEVELS.debug <= logLevel) {
if (LOGLEVELS.debug <= LOGLEVELS[logLevel]) {
log(logger.debug, args);
}
};
Expand Down
19 changes: 8 additions & 11 deletions src/services/destination/postTransformation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import { generateErrorObject } from '../../v0/util';
import tags from '../../v0/util/tags';
import { ErrorReportingService } from '../errorReporting';
import { MiscService } from '../misc';
import logger from '../../logger';

const defaultErrorMessages = {
router: '[Router Transform] Error occurred while processing the payload.',
Expand Down Expand Up @@ -68,7 +68,7 @@
error: errObj.message || '[Processor Transform] Error occurred while processing the payload.',
statTags: errObj.statTags,
} as ProcessorTransformationResponse;
MiscService.logError(
logger.error(
errObj.message || '[Processor Transform] Error occurred while processing the payload.',
metaTo.errorDetails,
);
Expand Down Expand Up @@ -109,7 +109,7 @@
...resp.statTags,
...metaTo.errorDetails,
};
MiscService.logError(resp.error || defaultErrorMessages.router, metaTo.errorDetails);
logger.error(resp.error || defaultErrorMessages.router, metaTo.errorDetails);
stats.increment('event_transform_failure', metaTo.errorDetails);
} else {
stats.increment('event_transform_success', {
Expand Down Expand Up @@ -138,7 +138,7 @@
error: errObj.message || defaultErrorMessages.router,
statTags: errObj.statTags,
} as RouterTransformationResponse;
MiscService.logError(errObj.message || defaultErrorMessages.router, metaTo.errorDetails);
logger.error(errObj.message || defaultErrorMessages.router, metaTo.errorDetails);
ErrorReportingService.reportError(error, metaTo.errorContext, resp);
stats.increment('event_transform_failure', metaTo.errorDetails);
return resp;
Expand All @@ -156,7 +156,7 @@
error: errObj.message || defaultErrorMessages.delivery,
statTags: errObj.statTags,
} as RouterTransformationResponse;
MiscService.logError(error as string, metaTo.errorDetails);
logger.error(error as string, metaTo.errorDetails);
ErrorReportingService.reportError(error, metaTo.errorContext, resp);
return resp;
}
Expand Down Expand Up @@ -187,10 +187,7 @@
const errObj = generateErrorObject(error, metaTo.errorDetails, false);
const metadataArray = metaTo.metadatas;
if (!Array.isArray(metadataArray)) {
MiscService.logError(
'Proxy v1 endpoint error : metadataArray is not an array',
metaTo.errorDetails,
);
logger.error('Proxy v1 endpoint error : metadataArray is not an array', metaTo.errorDetails);

Check warning on line 190 in src/services/destination/postTransformation.ts

View check run for this annotation

Codecov / codecov/patch

src/services/destination/postTransformation.ts#L190

Added line #L190 was not covered by tests
// Panic
throw new PlatformError('Proxy v1 endpoint error : metadataArray is not an array');
}
Expand All @@ -215,7 +212,7 @@
authErrorCategory: errObj.authErrorCategory,
}),
} as DeliveryV1Response;
MiscService.logError(errObj.message, metaTo.errorDetails);
logger.error(errObj.message, metaTo.errorDetails);
ErrorReportingService.reportError(error, metaTo.errorContext, resp);
return resp;
}
Expand All @@ -233,7 +230,7 @@
authErrorCategory: errObj.authErrorCategory,
}),
} as UserDeletionResponse;
MiscService.logError(errObj.message, metaTo.errorDetails);
logger.error(errObj.message, metaTo.errorDetails);
ErrorReportingService.reportError(error, metaTo.errorContext, resp);
return resp;
}
Expand Down
9 changes: 1 addition & 8 deletions src/services/misc.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
/* eslint-disable global-require, import/no-dynamic-require */
import { LoggableExtraData } from '@rudderstack/integrations-lib';
import fs from 'fs';
import { Context } from 'koa';
import path from 'path';
import { DestHandlerMap } from '../constants/destinationCanonicalNames';
import { getCPUProfile, getHeapProfile } from '../middleware';
import { ErrorDetailer, Metadata } from '../types';
import logger from '../logger';
import { Metadata } from '../types';

export class MiscService {
public static getDestHandler(dest: string, version: string) {
Expand Down Expand Up @@ -76,9 +74,4 @@ export class MiscService {
public static async getHeapProfile() {
return getHeapProfile();
}

public static logError(message: string, errorDetailer: ErrorDetailer) {
const loggableExtraData: Partial<LoggableExtraData> = logger.getLogMetadata(errorDetailer);
logger.error(message || '', loggableExtraData);
}
}
3 changes: 1 addition & 2 deletions src/util/redis/redisConnector.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ const fs = require('fs');
const path = require('path');
const version = 'v0';
const { RedisDB } = require('./redisConnector');
const logger = require('../../logger');
jest.mock('ioredis', () => require('../../../test/__mocks__/redis'));

const sourcesList = ['shopify'];
Expand Down Expand Up @@ -56,7 +55,7 @@ describe(`Source Tests`, () => {
data.forEach((dataPoint, index) => {
it(`${index}. ${source} - ${dataPoint.description}`, async () => {
try {
const output = await transformer.process(dataPoint.input, logger);
const output = await transformer.process(dataPoint.input);
expect(output).toEqual(dataPoint.output);
} catch (error) {
expect(error.message).toEqual(dataPoint.output.error);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
query: queryString,
};
const searchStreamEndpoint = `${BASE_ENDPOINT}/${params.customerId}/googleAds:searchStream`;
logger.requestLog(`[${destType.toUpperCase()}] conversion enhancement request`, {
logger.requestLog(`[${destType.toUpperCase()}] get conversion action id request`, {
metadata,
requestDetails: { url: searchStreamEndpoint, body: data, method },
});
Expand Down Expand Up @@ -75,7 +75,7 @@
`"${JSON.stringify(
get(gaecConversionActionIdResponse, ERROR_MSG_PATH, '')
? get(gaecConversionActionIdResponse, ERROR_MSG_PATH, '')
: response,

Check warning on line 78 in src/v0/destinations/google_adwords_enhanced_conversions/networkHandler.js

View check run for this annotation

Codecov / codecov/patch

src/v0/destinations/google_adwords_enhanced_conversions/networkHandler.js#L78

Added line #L78 was not covered by tests
)} during Google_adwords_enhanced_conversions response transformation"`,
status,
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ const getConversionActionId = async ({ headers, params, metadata }) => {
});
searchStreamResponse = processAxiosResponse(searchStreamResponse);
const { response, status, headers: responseHeaders } = searchStreamResponse;
logger.responseLog(`[${destType.toUpperCase()}] get conversion custom variable`, {
logger.responseLog(`[${destType.toUpperCase()}] get conversion action id response`, {
metadata,
responseDetails: {
response,
Expand Down
Loading