@talks.converse/js-monitoring
Version:
Express monitoring middleware with Datadog and Prometheus backends, plus conditional logging.
49 lines (41 loc) • 2.07 kB
JavaScript
const helper = require('./helper');
/**
* Checks if an endpoint matches any of the default exclude regex patterns.
* @param {string} endpoint - The endpoint path to check.
* @returns {boolean} True if the endpoint is in the default exclude list, false otherwise.
*/
const isDefaultExcluded = (endpoint) => helper.DEFAULT_EXCLUDES.some((re) => re.test(endpoint || ''));
const loggingEndpointsInclude = process.env.LOGGING_ENDPOINTS_INCLUDE
const loggingEndpointsExclude = process.env.LOGGING_ENDPOINTS_EXCLUDE
/**
* Compiles include and exclude regex rules for logging endpoints from environment variables.
* @returns {Object} An object containing compiled include and exclude regex arrays.
*/
const buildLoggingEndpointsConfig = () => ({
include: helper.compileRegexList(loggingEndpointsInclude),
exclude: helper.compileRegexList(loggingEndpointsExclude),
});
/**
* Decides whether to log a request based on configured rules, endpoint path, and exclusion lists.
* If the request passes the rules and is not in the default excludes, logs the message details.
* @param {Object} message - The request message object.
* @param {string} [message.endpoint] - The endpoint path of the request.
* @param {string} [message.method] - The HTTP method of the request.
* @param {number} [message.statusCode] - The HTTP status code of the response.
* @param {Object} [message.query] - The query parameters of the request.
* @param {Object} [message.body] - The body of the request.
* @param {Object} [message.response] - The response body.
* @param {number} [message.latencyMs] - The latency in milliseconds.
*/
const loggingRequest = (message = {}) => {
const endpointPath = message.endpoint || '';
const loggingEndpointRules = buildLoggingEndpointsConfig();
// Must pass include/exclude config AND not be in default excludes
const passesRules = helper.isEndpointProcessed(endpointPath, loggingEndpointRules) && !isDefaultExcluded(endpointPath);
if (passesRules) {
console.log(message);
}
};
module.exports = {
loggingRequest,
};