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/detailed request logger #304

Draft
wants to merge 11 commits into
base: develop
Choose a base branch
from
5 changes: 4 additions & 1 deletion libs/logger/src/interceptors/common-http.interceptor.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { createMock } from '@golevelup/nestjs-testing';
import { CallHandler, ExecutionContext } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { of } from 'rxjs';
import { HttpLoggingInterceptor } from './common-http.interceptor';

describe('HttpLoggingInterceptor', () => {
let interceptor;
let configService;

beforeEach(() => {
interceptor = new HttpLoggingInterceptor();
configService = new ConfigService();
interceptor = new HttpLoggingInterceptor(configService);
});

it('should be defined', () => {
Expand Down
10 changes: 8 additions & 2 deletions libs/logger/src/interceptors/common-http.interceptor.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,30 @@
import { CallHandler, ExecutionContext, Injectable, Logger, NestInterceptor } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class HttpLoggingInterceptor implements NestInterceptor {
readonly logger = new Logger(HttpLoggingInterceptor.name);
#instanceID: string;

constructor(configService: ConfigService) {
this.#instanceID = configService.get('SERVER_INSTANCE_ID');
}

intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
let req = context.switchToHttp().getRequest();
let log = false;

if (context['contextType'] !== 'graphql') {
log = true;
this.logger.log(`START: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url}`);
this.logger.log(`START: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.#instanceID}`);
}

return next.handle().pipe(
tap(() => {
if (log) {
this.logger.log(`STOP: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url}`);
this.logger.log(`STOP: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.#instanceID}`);
}
}),
);
Expand Down
16 changes: 12 additions & 4 deletions libs/logger/src/logger.module.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import { Module } from '@nestjs/common';
import { DynamicModule, Module } from '@nestjs/common';
import { OMSLogger } from './oms/oms.logger.service';

@Module({
providers: [ OMSLogger ],
exports: [ OMSLogger ],
providers: [
OMSLogger
],
exports: [OMSLogger],
})
export class LoggerModule {}
export class LoggerModule {
static register(): DynamicModule {
return {
module: LoggerModule
};
}
}
9 changes: 7 additions & 2 deletions libs/logger/src/oms/oms.logger.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import { ConfigService } from '@nestjs/config';
import { Test, TestingModule } from '@nestjs/testing';
import { OMSLogger } from './oms.logger.service';

describe('OMSLogger', () => {
let service: OMSLogger;
let configService: ConfigService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [OMSLogger],
providers: [OMSLogger, ConfigService],
}).compile();

service = await module.resolve<OMSLogger>(OMSLogger);
configService = await module.resolve<ConfigService>(ConfigService);
jest.spyOn(console, 'log').mockImplementation(() => 'test');

process.stdout.isTTY = false;
Expand Down Expand Up @@ -52,13 +55,15 @@ describe('OMSLogger', () => {

describe('OMSLogger - with mocked interactive console', () => {
let service: OMSLogger;
let configService: ConfigService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [OMSLogger],
providers: [OMSLogger, ConfigService],
}).compile();

service = await module.resolve<OMSLogger>(OMSLogger);
configService = await module.resolve<ConfigService>(ConfigService);
jest.spyOn(console, 'log').mockImplementation(() => 'test');

process.stdout.isTTY = true;
Expand Down
10 changes: 9 additions & 1 deletion libs/logger/src/oms/oms.logger.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { ConsoleLogger, Injectable, Scope } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { OMSLogLevel } from './OMSLog.interface';

@Injectable({ scope: Scope.TRANSIENT })
export class OMSLogger extends ConsoleLogger {
#instanceID: string;
constructor(private configService: ConfigService) {
super();
this.#instanceID = configService.get('SERVER_INSTANCE_ID');
}

private print(logLevel: OMSLogLevel, message: string, context?: string, stackTrace?: string) {
let currentContext = context;
if (typeof context === 'undefined') {
Expand All @@ -15,6 +22,7 @@ export class OMSLogger extends ConsoleLogger {
msg: message,
logger: currentContext,
stack_trace: stackTrace,
instanceID: this.#instanceID,
};

console.log(JSON.stringify(logEntry));
Expand All @@ -41,4 +49,4 @@ export class OMSLogger extends ConsoleLogger {
verbose(message: string, context?: string) {
process.stdout.isTTY ? super.verbose.apply(this, arguments) : this.print(OMSLogLevel.VERBOSE, message, context);
}
}
}
2 changes: 1 addition & 1 deletion libs/oidc/src/filters/http-exception.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { SSRPagesService } from '../services';
export class HttpExceptionFilter implements ExceptionFilter {
readonly logger = new Logger(HttpExceptionFilter.name);

constructor(private ssrPagesService: SSRPagesService) {}
constructor(private ssrPagesService: SSRPagesService) { }

catch(exception: any, host: ArgumentsHost) {
const ctx = host.switchToHttp();
Expand Down
8 changes: 4 additions & 4 deletions libs/oidc/src/oidc.module.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { TestingModule, Test } from '@nestjs/testing';
import { createMock } from '@golevelup/nestjs-testing';
import { MiddlewareConsumer } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { Issuer } from 'openid-client';
import { MOCK_ISSUER_INSTANCE, MOCK_OIDC_MODULE_OPTIONS } from './mocks';
import { OidcModule } from './oidc.module';
import { MOCK_OIDC_MODULE_OPTIONS, MOCK_ISSUER_INSTANCE } from './mocks';
import { MiddlewareConsumer } from '@nestjs/common';

describe('OidcModule', () => {
describe(OidcModule.name, () => {
describe('register sync', () => {
let module: TestingModule;

Expand Down
6 changes: 4 additions & 2 deletions libs/oidc/src/oidc.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { DynamicModule, Global, MiddlewareConsumer, Module, NestModule, Provider, RequestMethod } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { APP_FILTER, APP_GUARD } from '@nestjs/core';
import { JwtModule } from '@nestjs/jwt';
import { TenantSwitchController } from './controllers';
Expand Down Expand Up @@ -30,6 +31,7 @@ import { SessionSerializer } from './utils/session.serializer';
TokenGuard,
GuestTokenGuard,
OidcService,
ConfigService,
SSRPagesService,
{
provide: APP_GUARD,
Expand Down Expand Up @@ -66,7 +68,7 @@ export class OidcModule implements NestModule {
{
provide: OIDC_MODULE_OPTIONS,
useValue: options,
},
}
],
};
}
Expand All @@ -75,7 +77,7 @@ export class OidcModule implements NestModule {
return {
module: OidcModule,
imports: options.imports,
providers: [...this.createAsyncProviders(options)],
providers: this.createAsyncProviders(options),
};
}

Expand Down
21 changes: 11 additions & 10 deletions libs/oidc/src/services/oidc.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ConfigService } from '@nestjs/config';
import axios from 'axios';
import * as handlebars from 'handlebars';
import { JWKS } from 'jose';
Expand All @@ -11,7 +12,7 @@ import { SSRPagesService } from './ssr-pages.service';
import passport = require('passport');

describe('OidcService', () => {
let service = new OidcService(MOCK_OIDC_MODULE_OPTIONS, new SSRPagesService());
let service = new OidcService(MOCK_OIDC_MODULE_OPTIONS, new ConfigService(), new SSRPagesService());
let options: OidcModuleOptions = MOCK_OIDC_MODULE_OPTIONS;
const idpKey = 'idpKey';

Expand Down Expand Up @@ -154,7 +155,7 @@ describe('OidcService', () => {
it('should call passport authenticate for single tenant login', async () => {
service.strategy = new OidcStrategy(service, idpKey);
const spy = jest.spyOn(passport, 'authenticate').mockImplementation(() => {
return (req, res, next) => {};
return (req, res, next) => { };
});
await service.login(req, res, next, params);
expect(spy).toHaveBeenCalled();
Expand All @@ -167,7 +168,7 @@ describe('OidcService', () => {
channelType: 'b2c',
};
const spy = jest.spyOn(passport, 'authenticate').mockImplementation(() => {
return (req, res, next) => {};
return (req, res, next) => { };
});
await service.login(req, res, next, params);
expect(spy).toHaveBeenCalled();
Expand All @@ -180,7 +181,7 @@ describe('OidcService', () => {
tenantId: 'tenant',
};
const spy = jest.spyOn(passport, 'authenticate').mockImplementation(() => {
return (req, res, next) => {};
return (req, res, next) => { };
});
await service.login(req, res, next, params);
expect(spy).toHaveBeenCalled();
Expand Down Expand Up @@ -211,7 +212,7 @@ describe('OidcService', () => {

const spy = jest.spyOn(passport, 'authenticate').mockImplementation((strategy, options, cb) => {
cb();
return (req, res, next) => {};
return (req, res, next) => { };
});

await service.login(req, res, next, params);
Expand All @@ -233,7 +234,7 @@ describe('OidcService', () => {
const spy = jest.spyOn(passport, 'authenticate').mockImplementation((strategy, options, cb) => {
const user = {};
cb(null, user, null);
return (req, res, next) => {};
return (req, res, next) => { };
});

await service.login(req, res, next, params);
Expand All @@ -254,7 +255,7 @@ describe('OidcService', () => {

const spy = jest.spyOn(passport, 'authenticate').mockImplementation((strategy, options, cb) => {
cb(null, {}, null);
return (req, res, next) => {};
return (req, res, next) => { };
});

await service.login(req, res, next, params);
Expand All @@ -279,7 +280,7 @@ describe('OidcService', () => {
state: options.state,
};
cb(null, {}, null);
return (req, res, next) => {};
return (req, res, next) => { };
});

const spyRes = jest.spyOn(res, 'redirect');
Expand Down Expand Up @@ -332,7 +333,7 @@ describe('OidcService', () => {
state: options.state,
};
cb(null, {}, null);
return (req, res, next) => {};
return (req, res, next) => { };
});

const spyRes = jest.spyOn(res, 'redirect');
Expand Down Expand Up @@ -364,7 +365,7 @@ describe('OidcService', () => {
state: options.state,
};
cb(null, {}, null);
return (req, res, next) => {};
return (req, res, next) => { };
});

const spyRes = jest.spyOn(res, 'redirect');
Expand Down
Loading
Loading