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

Feature: configure logging wrapper #152

Merged
merged 21 commits into from
Apr 30, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
1567d22
feat(logging-wrapper): started configuring package
SamSalvatico Apr 23, 2024
ad436a1
feat(logging-wrapper): added logging wrapper entities
SamSalvatico Apr 23, 2024
8e19fd7
feat(logging-wrapper): add linter
SamSalvatico Apr 23, 2024
862640d
Added fastify wrapper
SamSalvatico Apr 23, 2024
b916ad7
MInified jest config js
SamSalvatico Apr 23, 2024
a548e1a
Updated docs removing Jest
SamSalvatico Apr 23, 2024
b0c8953
Removed jest
SamSalvatico Apr 23, 2024
6508bbc
Fixed lint config
SamSalvatico Apr 23, 2024
f1dde5f
Merge branch 'dev' into feature/configure-logging-wrapper
SamSalvatico Apr 23, 2024
f4dbd01
Updated deps
SamSalvatico Apr 23, 2024
a60a8bb
Merge branch 'dev' into feature/configure-logging-wrapper
SamSalvatico Apr 24, 2024
9a70c3a
Merge branch 'dev' into feature/configure-logging-wrapper
SamSalvatico Apr 26, 2024
40c8830
Merge branch 'dev' into feature/configure-logging-wrapper
SamSalvatico Apr 29, 2024
81ac256
Feature: logging wrapper tests (#157)
SamSalvatico Apr 29, 2024
baef20b
Merge branch 'dev' into feature/configure-logging-wrapper
SamSalvatico Apr 29, 2024
755f9a7
Merge branch 'dev' into feature/configure-logging-wrapper
SamSalvatico Apr 29, 2024
8e02c35
Aligned payments lock
SamSalvatico Apr 29, 2024
da91510
updated to next 14.2.2
SamSalvatico Apr 29, 2024
08dfe48
Merge branch 'dev' into feature/configure-logging-wrapper
SamSalvatico Apr 29, 2024
2912ff3
Realigned to dev
SamSalvatico Apr 30, 2024
18e22f9
Merge branch 'dev' into feature/configure-logging-wrapper
SamSalvatico Apr 30, 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
3,710 changes: 3,279 additions & 431 deletions package-lock.json

Large diffs are not rendered by default.

18 changes: 18 additions & 0 deletions packages/logging-wrapper/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"parser": "@typescript-eslint/parser",
"extends": [
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended",
"eslint:recommended"
],
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module"
},
"rules": {
},
"env": {
"browser": true,
"node": true
}
}
195 changes: 195 additions & 0 deletions packages/logging-wrapper/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/

/** @type {import('jest').Config} */
const config = {
// All imported modules in your tests should be mocked automatically
// automock: false,

// Stop running tests after `n` failures
// bail: 0,

// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/xq/mbcjtpjn68s5tcc_65r9vjvh0000gn/T/jest_dx",

// Automatically clear mock calls, instances, contexts and results before every test
// clearMocks: false,

// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,

// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,

// The directory where Jest should output its coverage files
// coverageDirectory: undefined,

// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],

// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",

// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],

// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,

// A path to a custom dependency extractor
// dependencyExtractor: undefined,

// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,

// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },

// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],

// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,

// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,

// A set of global variables that need to be available in all test environments
// globals: {},

// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",

// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],

// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],

// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},

// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],

// Activates notifications for test results
// notify: false,

// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",

// A preset that is used as a base for Jest's configuration
preset: "ts-jest",

// Run tests from one or more projects
// projects: undefined,

// Use this configuration option to add custom reporters to Jest
// reporters: undefined,

// Automatically reset mock state before every test
// resetMocks: false,

// Reset the module registry before running each individual test
// resetModules: false,

// A path to a custom resolver
// resolver: undefined,

// Automatically restore mock state and implementation before every test
// restoreMocks: false,

// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,

// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],

// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",

// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],

// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],

// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,

// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],

// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",

// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},

// Adds a location field to test results
// testLocationInResults: false,

// The glob patterns Jest uses to detect test files
testMatch: ["**/__tests__/**/*.(spec|test).[jt]s?(x)"],

// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],

// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],

// This option allows the use of a custom results processor
// testResultsProcessor: undefined,

// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",

// A map from regular expressions to paths to transformers
// transform: undefined,

// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],

// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,

// Indicates whether each individual test should be reported during the run
// verbose: undefined,

// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],

// Whether to use watchman for file crawling
// watchman: true,
};

module.exports = config;
34 changes: 34 additions & 0 deletions packages/logging-wrapper/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "logging-wrapper",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest",
"build": "tsc -p tsconfig.json",
"lint": "eslint . --ext .ts",
"lint:fix": "eslint . --ext .ts --fix"
},
"keywords": [],
"author": "[email protected]",
"license": "ISC",
"dependencies": {
"@fastify/error": "^3.4.1",
"fastify": "^4.26.2",
"hyperid": "^3.2.0"
},
"devDependencies": {
"@tsconfig/node20": "^20.1.4",
"@types/jest": "^29.5.12",
"@types/node": "^20.12.7",
"@typescript-eslint/eslint-plugin": "^7.7.1",
"@typescript-eslint/parser": "^7.7.1",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.1.3",
"jest": "^29.7.0",
"prettier": "^3.2.5",
"ts-jest": "^29.1.2",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Usually, we avoid Jest while testing Node.js applications in favour of other test frameworks (like TAP) due to some known issues.

Copy link
Contributor Author

@SamSalvatico SamSalvatico Apr 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ouch!
I've used that because we have explicit request of do that in our docs

Anyway, thank you, I will update tests and docs!

"typescript": "^5.4.5"
}
}
139 changes: 139 additions & 0 deletions packages/logging-wrapper/src/fastify-logging-wrapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import {
FastifyReply,
FastifyServerOptions,
FastifyInstance,
FastifyRequest,
} from "fastify";
import hyperid from "hyperid";
import { LogMessages, REQUEST_ID_LOG_LABEL } from "./logging-wrapper-entities";
import {
getLoggerConfiguration,
getLoggingContextError,
getPartialLoggingContextError,
parseErrorClass,
parseFullLoggingRequest,
resetLoggingContext,
setLoggingContext,
} from "./logging-wrapper";
import { pino, DestinationStream } from "pino";
import createError, { FastifyError } from "@fastify/error";

const hyperidInstance = hyperid({ fixedLength: true, urlSafe: true });

const buildErrorResponse = (error: FastifyError, request: FastifyRequest) => ({
errors: [
{
code: parseErrorClass(error),
detail: error.message,
request_id: request.id,
},
],
});

// The error handler below is the same as the original one in Fastify,
// just without unwanted log entries
// I've opened an issue to fastify to ask them if we could avoid logging
// those entries when disableRequestLogging is true
// https://github.com/fastify/fastify/issues/5409
const initializeErrorHandler = (server: FastifyInstance): void => {
const setErrorHeaders = (
error: null | {
headers?: { [x: string]: string | number | string[] | undefined };
status?: number;
statusCode?: number;
},
reply: FastifyReply,
) => {
const res = reply.raw;
let statusCode = res.statusCode;
statusCode = statusCode >= 400 ? statusCode : 500;
// treat undefined and null as same
if (error != null) {
if (error.headers !== undefined) {
reply.headers(error.headers);
}
if (error.status && error.status >= 400) {
statusCode = error.status;
} else if (error.statusCode && error.statusCode >= 400) {
statusCode = error.statusCode;
}
}
res.statusCode = statusCode;
};

server.setErrorHandler(function (error, request, reply) {
setErrorHeaders(error, reply);
if (!reply.statusCode || reply.statusCode === 200) {
const statusCode = error.statusCode ?? 500;
reply.code(statusCode >= 400 ? statusCode : 500);
}

reply.send(buildErrorResponse(error, request));
GiuliaTeggi marked this conversation as resolved.
Show resolved Hide resolved
});
};

// The error handler below is the same as the original one in Fastify,
// just without unwanted log entries
const initializeNotFoundHandler = (server: FastifyInstance): void => {
server.setNotFoundHandler((request: FastifyRequest, reply: FastifyReply) => {
const { url, method } = request.raw;
const message = `Route ${method}:${url} not found`;

const error = createError("FST_ERR_NOT_FOUND", message, 404)();
setLoggingContext({
error,
});

request.log.error({ error: getLoggingContextError() }, LogMessages.Error);
reply.code(404).send(buildErrorResponse(error, request));
});
};

export const initializeLoggingHooks = (
server: FastifyInstance,
overrideErrorHandler: boolean = true,
): void => {
server.addHook("preHandler", (request, _reply, done) => {
setLoggingContext({ request });
request.log.info(
{ request: parseFullLoggingRequest(request) },
LogMessages.NewRequest,
);
done();
});

server.addHook("onResponse", (_req, reply, done) => {
setLoggingContext({ response: reply });
reply.log.info(LogMessages.Response);
// Include error in API Track if exists
reply.log.info(
{ error: getPartialLoggingContextError() },
LogMessages.ApiTrack,
);
resetLoggingContext();
done();
});

server.addHook("onError", (request, _reply, error, done) => {
setLoggingContext({ error });

request.log.error({ error: getLoggingContextError() }, LogMessages.Error);

done();
});

if (overrideErrorHandler) {
initializeErrorHandler(server);
initializeNotFoundHandler(server);
}
};

export const getLoggingConfiguration = (
loggerDestination?: DestinationStream,
): FastifyServerOptions => ({
logger: pino(getLoggerConfiguration(), loggerDestination),
disableRequestLogging: true,
genReqId: () => hyperidInstance(),
requestIdLogLabel: REQUEST_ID_LOG_LABEL,
requestIdHeader: false,
});
Loading