-
Notifications
You must be signed in to change notification settings - Fork 16
BC-8556 implement request logging in nestjs #5401
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
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
167c336
BC-8559 implement request logging in nestjs
Loki-Afro cd10483
BC-7906 - Remove tldraw legacy code (#5390)
bischofmax 41a2a8d
N21-2313 Improve schulconnex group provisioning runtime (#5394)
MarvinOehlerkingCap 764535f
N21-2317 Skip failed migrations in migration wizard (#5398)
MarvinOehlerkingCap b6c27cf
BC-8519 - add room owner role (#5393)
hoeppner-dataport 811b693
BC-8571 adding index to files.securityCheck.requestToken (#5399)
Loki-Afro ab5050c
Merge branch 'main' into bc-8556
Loki-Afro ce87e6d
cleanup imports, renamed function
Loki-Afro 9603b79
Merge branch 'main' into bc-8556
Loki-Afro 5059962
review comments
Loki-Afro 06fbbcc
clean imports
Loki-Afro 2745a28
clean imports
Loki-Afro 6bd91be
Merge branch 'main' into bc-8556
Loki-Afro e40ddb4
Merge branch 'main' into bc-8556
Loki-Afro 5dce53d
added complicated test to reach 100%
Loki-Afro fffcadc
import order
Loki-Afro File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
99 changes: 99 additions & 0 deletions
99
apps/server/src/apps/helpers/request-logger-middleware.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| import { Configuration } from '@hpi-schul-cloud/commons/lib'; | ||
| import { Logger } from '@nestjs/common'; | ||
| import { Request, Response, NextFunction } from 'express'; | ||
| import { createRequestLoggerMiddleware } from './request-logger-middleware'; | ||
|
|
||
| jest.mock('@hpi-schul-cloud/commons/lib', () => { | ||
| return { | ||
| Configuration: { | ||
| get: jest.fn(), | ||
| }, | ||
| }; | ||
| }); | ||
|
|
||
| describe('RequestLoggerMiddleware', () => { | ||
| let mockRequest: Partial<Request>; | ||
| let mockResponse: Partial<Response>; | ||
| let nextFunction: NextFunction; | ||
| let loggerSpy: jest.SpyInstance; | ||
| let errorLoggerSpy: jest.SpyInstance; | ||
|
|
||
| beforeEach(() => { | ||
| mockRequest = { | ||
| method: 'GET', | ||
| originalUrl: '/test', | ||
| }; | ||
|
|
||
| mockResponse = { | ||
| statusCode: 200, | ||
| get: jest.fn(), | ||
| on: jest.fn(), | ||
| }; | ||
|
|
||
| nextFunction = jest.fn(); | ||
|
|
||
| loggerSpy = jest.spyOn(Logger.prototype, 'log'); | ||
| errorLoggerSpy = jest.spyOn(Logger.prototype, 'error'); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| it('should call next() when logging is disabled', () => { | ||
| jest.spyOn(Configuration, 'get').mockReturnValue(false); | ||
|
|
||
| const middleware = createRequestLoggerMiddleware(); | ||
| middleware(mockRequest as Request, mockResponse as Response, nextFunction); | ||
|
|
||
| expect(nextFunction).toHaveBeenCalled(); | ||
| expect(mockResponse.on).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should log request details when logging is enabled', () => { | ||
| jest.spyOn(Configuration, 'get').mockReturnValue(true); | ||
|
|
||
| jest.spyOn(process, 'hrtime').mockReturnValueOnce([0, 0]); | ||
| jest.spyOn(mockResponse, 'get').mockImplementation().mockReturnValue('100'); | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/ban-types | ||
| let finishCallback: Function | undefined; | ||
| // eslint-disable-next-line @typescript-eslint/ban-types | ||
| mockResponse.on = jest.fn().mockImplementation((event: string, callback: Function) => { | ||
| finishCallback = callback; | ||
| }); | ||
|
|
||
| const middleware = createRequestLoggerMiddleware(); | ||
| middleware(mockRequest as Request, mockResponse as Response, nextFunction); | ||
|
|
||
| expect(nextFunction).toHaveBeenCalled(); | ||
| expect(mockResponse.on).toHaveBeenCalledWith('finish', expect.any(Function)); | ||
|
|
||
| // Simulate response finish | ||
| jest.spyOn(process, 'hrtime').mockReturnValueOnce([1, 0]); | ||
|
|
||
| // Make sure callback was set before calling it | ||
| expect(finishCallback).toBeDefined(); | ||
| finishCallback?.(); | ||
|
|
||
| expect(loggerSpy).toHaveBeenCalledWith('GET /test 200 1000ms 100'); | ||
| }); | ||
|
|
||
| it('should handle errors during logging', () => { | ||
| jest.spyOn(Configuration, 'get').mockReturnValue(true); | ||
| // eslint-disable-next-line @typescript-eslint/ban-types | ||
| mockResponse.on = jest.fn().mockImplementation((event: string, callback: Function) => { | ||
| callback(); | ||
| }); | ||
|
|
||
| // Force an error by making response.get throw | ||
| mockResponse.get = jest.fn().mockImplementation(() => { | ||
| throw new Error('Test error'); | ||
| }); | ||
|
|
||
| const middleware = createRequestLoggerMiddleware(); | ||
| middleware(mockRequest as Request, mockResponse as Response, nextFunction); | ||
|
|
||
| expect(errorLoggerSpy).toHaveBeenCalledWith('unable to write accesslog', Error('Test error')); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import { Request, Response, NextFunction } from 'express'; | ||
| import { Configuration } from '@hpi-schul-cloud/commons/lib'; | ||
| import { Logger } from '@nestjs/common'; | ||
|
|
||
| export const createRequestLoggerMiddleware = (): (( | ||
| request: Request, | ||
| response: Response, | ||
| next: NextFunction | ||
| ) => void) => { | ||
| const enabled = Configuration.get('REQUEST_LOGGING_ENABLED') as boolean; | ||
| const logger = new Logger('REQUEST_LOG'); | ||
|
|
||
| return (request: Request, response: Response, next: NextFunction): void => { | ||
| if (enabled) { | ||
| const startAt = process.hrtime(); | ||
| const { method, originalUrl } = request; | ||
|
|
||
| response.on('finish', () => { | ||
| try { | ||
| const { statusCode } = response; | ||
| const contentLength = response.get('content-length') || 'unknown'; | ||
| const diff = process.hrtime(startAt); | ||
| const responseTime = diff[0] * 1e3 + diff[1] * 1e-6; | ||
| logger.log(`${method} ${originalUrl} ${statusCode} ${responseTime}ms ${contentLength}`); | ||
| } catch (error) { | ||
| logger.error('unable to write accesslog', error); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| next(); | ||
| }; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.