Make parse-server cloud code logging closer parse.com legacy (#2550)
* Make parse-server cloud code logging much to parse.com legacy. (fixes #2501) 1. More closely mimic the wording. Include the user id. 2. Truncate input and result at 1k char. 3. Use more sensible metadata that would makes sense to index. The guideline I used was: if it makes sense to filter on, put it in metadata. If it makes sense to "free text" search on, then put it in the message. - file and console output, logging an object does not do what on might expect. For example, logging a function's "params": ``` expected: info: Ran cloud function aFunction for user qWHLVEsbEe with: Input: {"foo":"bar","bar":"baz"} Result: "it worked!" functionName=aFunction, params= { foo: "bar", "bar": baz }, user=qWHLVEsbEe what you actually get: info: Ran cloud function aFunction for user qWHLVEsbEe with: Input: {"foo":"bar","bar":"baz"} Result: "it worked!" functionName=aFunction, foo=bar, bar=baz, user=qWHLVEsbEe ``` - logging highly variable metadata is pretty useless for indexing when logs are sent to a logging repository like elastic search. In that use case, you want to index stuff you expect to filter on like user, hook type. - finally, putting the same input and result data in both the metadata and the message makes each message much larger with no additional value (that I know of anyway :). 4. Change some of the naming of functions in trigger.js to make future work easier. I was confused about why there were three logging functions in trigger and it took me awhile to get that before hooks and after hooks are logged differently. I just changed the names to make it obvious at first glance. 5. Add some try/catches to help any future futzers see syntax errors, etc instead of just hanging. Some log examples from unit test output: ``` info: Ran cloud function loggerTest for user YUD2os1i5B with: Input: {} Result: {} functionName=loggerTest, user=YUD2os1i5B info: beforeSave triggered for MyObject for user nssehQ3wtz: Input: {} Result: {} className=MyObject, triggerType=beforeSave, user=nssehQ3wtz info: afterSave triggered for MyObject for user XdznQgTD0p: Input: {"createdAt":"2016-08-19T01:11:31.249Z","updatedAt":"2016-08-19T01:11:31.249Z","objectId":"POoOOLL89U"} className=MyObject, triggerType=afterSave, user=XdznQgTD0p error: beforeSave failed for MyObject for user 7JHqCZgnhf: Input: {} Error: {"code":141,"message":"uh oh!"} className=MyObject, triggerType=beforeSave, code=141, message=uh oh!, user=7JHqCZgnhf info: Ran cloud function aFunction for user YR3nOoT3r9 with: Input: {"foo":"bar"} Result: "it worked!" functionName=aFunction, user=YR3nOoT3r9 error: Failed running cloud function aFunction for user Xm6NpOyuMC with: Input: {"foo":"bar"} Error: {"code":141,"message":"it failed!"} functionName=aFunction, code=141, message=it failed!, user=Xm6NpOyuMC info: Ran cloud function aFunction for user CK1lvkmaLg with: Input: {"longString":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus lobortis semper diam, ac euismod diam pharetra sed. Etiam eget efficitur neque. Proin nec diam mi. Sed ut purus dolor. Nulla nulla nibh, ornare vitae ornare et, scelerisque rutrum eros. Mauris venenatis tincidunt turpis a mollis. Donec gravida eget enim in luctus.\n\nSed porttitor commodo orci, ut pretium eros convallis eget. Curabitur pretium velit in odio dictum luctus. Vivamus ac tristique arcu, a semper tellus. Morbi euismod purus dapibus vestibulum sagittis. Nunc dapibus vehicula leo at scelerisque. Donec porta mauris quis nulla imperdiet consectetur. Curabitur sagittis eleifend arcu eget elementum. Aenean interdum tincidunt ornare. Pellentesque sit amet interdum tortor. Pellentesque blandit nisl eget euismod consequat. Etiam feugiat felis sit amet porta pulvinar. Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n\nNulla faucibus sem ipsum, at rhoncus diam pulvinar at. Vivamus consectetur, diam... (truncated) Result: {"longString":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus lobortis semper diam, ac euismod diam pharetra sed. Etiam eget efficitur neque. Proin nec diam mi. Sed ut purus dolor. Nulla nulla nibh, ornare vitae ornare et, scelerisque rutrum eros. Mauris venenatis tincidunt turpis a mollis. Donec gravida eget enim in luctus.\n\nSed porttitor commodo orci, ut pretium eros convallis eget. Curabitur pretium velit in odio dictum luctus. Vivamus ac tristique arcu, a semper tellus. Morbi euismod purus dapibus vestibulum sagittis. Nunc dapibus vehicula leo at scelerisque. Donec porta mauris quis nulla imperdiet consectetur. Curabitur sagittis eleifend arcu eget elementum. Aenean interdum tincidunt ornare. Pellentesque sit amet interdum tortor. Pellentesque blandit nisl eget euismod consequat. Etiam feugiat felis sit amet porta pulvinar. Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n\nNulla faucibus sem ipsum, at rhoncus diam pulvinar at. Vivamus consectetur, diam... (truncated) functionName=aFunction, user=CK1lvkmaLg ``` * Implement PR comments: - add back params to metadata and add back to the test - use screaming snake case for conts * fix typo
This commit is contained in:
committed by
Florent Vilmart
parent
277df54dc8
commit
5f67caefde
@@ -4,6 +4,8 @@ import AdaptableController from './AdaptableController';
|
||||
import { LoggerAdapter } from '../Adapters/Logger/LoggerAdapter';
|
||||
|
||||
const MILLISECONDS_IN_A_DAY = 24 * 60 * 60 * 1000;
|
||||
const LOG_STRING_TRUNCATE_LENGTH = 1000;
|
||||
const truncationMarker = '... (truncated)';
|
||||
|
||||
export const LogLevel = {
|
||||
INFO: 'info',
|
||||
@@ -16,7 +18,7 @@ export const LogOrder = {
|
||||
}
|
||||
|
||||
export class LoggerController extends AdaptableController {
|
||||
|
||||
|
||||
log(level, args) {
|
||||
args = [].concat(level, [...args]);
|
||||
this.adapter.log.apply(this.adapter, args);
|
||||
@@ -25,7 +27,7 @@ export class LoggerController extends AdaptableController {
|
||||
info() {
|
||||
return this.log('info', arguments);
|
||||
}
|
||||
|
||||
|
||||
error() {
|
||||
return this.log('error', arguments);
|
||||
}
|
||||
@@ -59,6 +61,15 @@ export class LoggerController extends AdaptableController {
|
||||
return null;
|
||||
}
|
||||
|
||||
truncateLogMessage(string) {
|
||||
if (string && string.length > LOG_STRING_TRUNCATE_LENGTH) {
|
||||
const truncated = string.substring(0, LOG_STRING_TRUNCATE_LENGTH) + truncationMarker;
|
||||
return truncated;
|
||||
}
|
||||
|
||||
return string;
|
||||
}
|
||||
|
||||
static parseOptions(options = {}) {
|
||||
let from = LoggerController.validDateTime(options.from) ||
|
||||
new Date(Date.now() - 7 * MILLISECONDS_IN_A_DAY);
|
||||
|
||||
@@ -78,20 +78,35 @@ export class FunctionsRouter extends PromiseRouter {
|
||||
}
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
var response = FunctionsRouter.createResponseObject((result) => {
|
||||
logger.info(`Ran cloud function ${req.params.functionName} with:\nInput: ${JSON.stringify(params)}\nResult: ${JSON.stringify(result.response.result)}`, {
|
||||
functionName: req.params.functionName,
|
||||
params,
|
||||
result: result.response.result
|
||||
});
|
||||
resolve(result);
|
||||
}, (error) => {
|
||||
logger.error(`Failed running cloud function ${req.params.functionName} with:\nInput: ${JSON.stringify(params)}\Error: ${JSON.stringify(error)}`, {
|
||||
functionName: req.params.functionName,
|
||||
params,
|
||||
error
|
||||
});
|
||||
reject(error);
|
||||
const userString = (req.auth && req.auth.user) ? req.auth.user.id : undefined;
|
||||
const cleanInput = logger.truncateLogMessage(JSON.stringify(params));
|
||||
var response = FunctionsRouter.createResponseObject((result) => {
|
||||
try {
|
||||
const cleanResult = logger.truncateLogMessage(JSON.stringify(result.response.result));
|
||||
logger.info(`Ran cloud function ${req.params.functionName} for user ${userString} `
|
||||
+ `with:\n Input: ${cleanInput }\n Result: ${cleanResult }`, {
|
||||
functionName: req.params.functionName,
|
||||
params,
|
||||
user: userString,
|
||||
});
|
||||
resolve(result);
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
}
|
||||
}, (error) => {
|
||||
try {
|
||||
logger.error(`Failed running cloud function ${req.params.functionName} for `
|
||||
+ `user ${userString} with:\n Input: ${cleanInput}\n Error: `
|
||||
+ JSON.stringify(error), {
|
||||
functionName: req.params.functionName,
|
||||
error,
|
||||
params,
|
||||
user: userString
|
||||
});
|
||||
reject(error);
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
// Force the keys before the function calls.
|
||||
Parse.applicationId = req.config.applicationId;
|
||||
|
||||
@@ -153,32 +153,36 @@ export function getResponseObject(request, resolve, reject) {
|
||||
}
|
||||
};
|
||||
|
||||
function logTrigger(triggerType, className, input) {
|
||||
if (triggerType.indexOf('after') != 0) {
|
||||
return;
|
||||
}
|
||||
logger.info(`${triggerType} triggered for ${className}\nInput: ${JSON.stringify(input)}`, {
|
||||
function userIdForLog(auth) {
|
||||
return (auth && auth.user) ? auth.user.id : undefined;
|
||||
}
|
||||
|
||||
function logTriggerAfterHook(triggerType, className, input, auth) {
|
||||
const cleanInput = logger.truncateLogMessage(JSON.stringify(input));
|
||||
logger.info(`${triggerType} triggered for ${className} for user ${userIdForLog(auth)}:\n Input: ${cleanInput}`, {
|
||||
className,
|
||||
triggerType,
|
||||
input
|
||||
user: userIdForLog(auth)
|
||||
});
|
||||
}
|
||||
|
||||
function logTriggerSuccess(triggerType, className, input, result) {
|
||||
logger.info(`${triggerType} triggered for ${className}\nInput: ${JSON.stringify(input)}\nResult: ${JSON.stringify(result)}`, {
|
||||
function logTriggerSuccessBeforeHook(triggerType, className, input, result, auth) {
|
||||
const cleanInput = logger.truncateLogMessage(JSON.stringify(input));
|
||||
const cleanResult = logger.truncateLogMessage(JSON.stringify(result));
|
||||
logger.info(`${triggerType} triggered for ${className} for user ${userIdForLog(auth)}:\n Input: ${cleanInput}\n Result: ${cleanResult}`, {
|
||||
className,
|
||||
triggerType,
|
||||
input,
|
||||
result
|
||||
user: userIdForLog(auth)
|
||||
});
|
||||
}
|
||||
|
||||
function logTriggerError(triggerType, className, input, error) {
|
||||
logger.error(`${triggerType} failed for ${className}\nInput: ${JSON.stringify(input)}\Error: ${JSON.stringify(error)}`, {
|
||||
function logTriggerErrorBeforeHook(triggerType, className, input, auth, error) {
|
||||
const cleanInput = logger.truncateLogMessage(JSON.stringify(input));
|
||||
logger.error(`${triggerType} failed for ${className} for user ${userIdForLog(auth)}:\n Input: ${cleanInput}\n Error: ${JSON.stringify(error)}`, {
|
||||
className,
|
||||
triggerType,
|
||||
input,
|
||||
error
|
||||
error,
|
||||
user: userIdForLog(auth)
|
||||
});
|
||||
}
|
||||
|
||||
@@ -187,7 +191,7 @@ function logTriggerError(triggerType, className, input, error) {
|
||||
// Will resolve successfully if no trigger is configured
|
||||
// Resolves to an object, empty or containing an object key. A beforeSave
|
||||
// trigger will set the object key to the rest format object to save.
|
||||
// originalParseObject is optional, we only need that for befote/afterSave functions
|
||||
// originalParseObject is optional, we only need that for before/afterSave functions
|
||||
export function maybeRunTrigger(triggerType, auth, parseObject, originalParseObject, config) {
|
||||
if (!parseObject) {
|
||||
return Promise.resolve({});
|
||||
@@ -197,25 +201,28 @@ export function maybeRunTrigger(triggerType, auth, parseObject, originalParseObj
|
||||
if (!trigger) return resolve();
|
||||
var request = getRequestObject(triggerType, auth, parseObject, originalParseObject, config);
|
||||
var response = getResponseObject(request, (object) => {
|
||||
logTriggerSuccess(triggerType, parseObject.className, parseObject.toJSON(), object);
|
||||
logTriggerSuccessBeforeHook(
|
||||
triggerType, parseObject.className, parseObject.toJSON(), object, auth);
|
||||
resolve(object);
|
||||
}, (error) => {
|
||||
logTriggerError(triggerType, parseObject.className, parseObject.toJSON(), error);
|
||||
logTriggerErrorBeforeHook(
|
||||
triggerType, parseObject.className, parseObject.toJSON(), auth, error);
|
||||
reject(error);
|
||||
});
|
||||
// Force the current Parse app before the trigger
|
||||
Parse.applicationId = config.applicationId;
|
||||
Parse.javascriptKey = config.javascriptKey || '';
|
||||
Parse.masterKey = config.masterKey;
|
||||
// For the afterSuccess / afterDelete
|
||||
logTrigger(triggerType, parseObject.className, parseObject.toJSON());
|
||||
|
||||
//AfterSave and afterDelete triggers can return a promise, which if they do, needs to be resolved before this promise is resolved,
|
||||
//so trigger execution is synced with RestWrite.execute() call.
|
||||
//If triggers do not return a promise, they can run async code parallel to the RestWrite.execute() call.
|
||||
// AfterSave and afterDelete triggers can return a promise, which if they
|
||||
// do, needs to be resolved before this promise is resolved,
|
||||
// so trigger execution is synced with RestWrite.execute() call.
|
||||
// If triggers do not return a promise, they can run async code parallel
|
||||
// to the RestWrite.execute() call.
|
||||
var triggerPromise = trigger(request, response);
|
||||
if(triggerType === Types.afterSave || triggerType === Types.afterDelete)
|
||||
{
|
||||
logTriggerAfterHook(triggerType, parseObject.className, parseObject.toJSON(), auth);
|
||||
if(triggerPromise && typeof triggerPromise.then === "function") {
|
||||
return triggerPromise.then(resolve, resolve);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user