Skip to content

Commit

Permalink
feat(all): allow to add extra metadata to logs
Browse files Browse the repository at this point in the history
The log methods now accept an object instead of multiple parameters to allow for the passing of
extra keys. These keys can be anything, from cloud-provider to anything else you want to add.
There's also a lot of refactoring and making some new interfaces for cleaner passing of parameters

BREAKING CHANGE: log methods now take an object as the second parameter instead of having 3 extra
optional parameters

fix #215 #228 #297
  • Loading branch information
jmcdo29 committed Oct 25, 2020
1 parent 327ebe9 commit 8599d35
Show file tree
Hide file tree
Showing 70 changed files with 522 additions and 1,010 deletions.
3 changes: 1 addition & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ name: CI
on:
pull_request:
branches:
- 'master'
- 'monorepo'
- 'main'
push:
branches:
- '*'
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/codeql-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ name: "CodeQL"

on:
push:
branches: [master]
branches: [main]
pull_request:
# The branches below must be a subset of the branches above
branches: [master]
branches: [main]
schedule:
- cron: '0 0 * * *'

Expand Down
1 change: 1 addition & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"singleQuote": true,
"arrowParens": "always",
"trailingComma": "all",
"printWidth": 100,
"overrides": [
{
"files": "*.md",
Expand Down
8 changes: 1 addition & 7 deletions integration/src/grpc/client/grpc-client.controller.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
import {
Controller,
Get,
Inject,
OnModuleInit,
UseFilters,
} from '@nestjs/common';
import { Controller, Get, Inject, OnModuleInit, UseFilters } from '@nestjs/common';
import { ClientGrpc } from '@nestjs/microservices';
import { ExceptionFilter } from './exception.filter';
import { HelloService } from './hello-service.interface';
Expand Down
13 changes: 2 additions & 11 deletions integration/src/kafka/client/kafka-client.controller.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
import {
Controller,
Get,
Inject,
OnModuleDestroy,
OnModuleInit,
UseFilters,
} from '@nestjs/common';
import { Controller, Get, Inject, OnModuleDestroy, OnModuleInit, UseFilters } from '@nestjs/common';
import { ClientKafka } from '@nestjs/microservices';
import { ExceptionFilter } from './exception.filter';

Expand All @@ -14,9 +7,7 @@ export class KafkaClientController implements OnModuleInit, OnModuleDestroy {
constructor(@Inject('KAFKA_SERVICE') private readonly kafka: ClientKafka) {}

async onModuleInit() {
['hello', 'error', 'skip'].forEach((key) =>
this.kafka.subscribeToResponseOf(`say.${key}`),
);
['hello', 'error', 'skip'].forEach((key) => this.kafka.subscribeToResponseOf(`say.${key}`));
}

onModuleDestroy() {
Expand Down
12 changes: 12 additions & 0 deletions integration/src/nested-module/app.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from '../../../benchmarks/interceptor/dist/app.service';

@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}

@Get()
sayHello() {
return this.appService.getHello();
}
}
12 changes: 12 additions & 0 deletions integration/src/nested-module/app.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { OgmaModule } from '@ogma/nestjs-module';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { LoggerModule } from './logger.module';

@Module({
imports: [LoggerModule, OgmaModule.forFeature(AppService)],
controllers: [AppController],
providers: [AppService],
})
export class NestedModule {}
12 changes: 12 additions & 0 deletions integration/src/nested-module/app.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Injectable } from '@nestjs/common';
import { OgmaLogger, OgmaService } from '@ogma/nestjs-module';

@Injectable()
export class AppService {
constructor(@OgmaLogger(AppService) private readonly logger: OgmaService) {}

getHello() {
this.logger.log('Hello NestedModule');
return { hello: 'World' };
}
}
14 changes: 14 additions & 0 deletions integration/src/nested-module/logger.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { OgmaModule } from '@ogma/nestjs-module';

@Module({
imports: [
OgmaModule.forRoot({
service: {
application: 'NestedModule',
},
interceptor: false,
}),
],
})
export class LoggerModule {}
3 changes: 1 addition & 2 deletions integration/src/rpc/client/rpc-client.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ import { ClientProxy } from '@nestjs/microservices';
import { ExceptionFilter } from './exception.filter';

@Controller()
export class RpcClientController
implements OnApplicationBootstrap, OnApplicationShutdown {
export class RpcClientController implements OnApplicationBootstrap, OnApplicationShutdown {
constructor(@Inject('RPC-SERVICE') private readonly micro: ClientProxy) {}

async onApplicationBootstrap() {
Expand Down
6 changes: 1 addition & 5 deletions integration/src/ws/ws.gateway.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets';
import {
BadRequestException,
UseFilters,
UseInterceptors,
} from '@nestjs/common';
import { BadRequestException, UseFilters, UseInterceptors } from '@nestjs/common';
import { OgmaInterceptor, OgmaSkip } from '@ogma/nestjs-module';
import { AppService } from '../app.service';
import { SimpleObject } from '../simple-object.model';
Expand Down
51 changes: 13 additions & 38 deletions integration/test/gql.spec.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,11 @@
import { HttpServer, INestApplication } from '@nestjs/common';
import { ExpressAdapter } from '@nestjs/platform-express';
import { FastifyAdapter } from '@nestjs/platform-fastify';
import {
AbstractInterceptorService,
OgmaInterceptor,
Type,
} from '@ogma/nestjs-module';
import { AbstractInterceptorService, OgmaInterceptor, Type } from '@ogma/nestjs-module';
import { GraphQLParser } from '@ogma/platform-graphql';
import { GraphQLFastifyParser } from '@ogma/platform-graphql-fastify';
import { GqlModule } from '../src/gql/gql.module';
import {
createTestModule,
getInterceptor,
gqlPromise,
serviceOptionsFactory,
} from './utils';
import { createTestModule, getInterceptor, gqlPromise, serviceOptionsFactory } from './utils';
import { color } from '@ogma/logger';

describe.each`
Expand Down Expand Up @@ -78,34 +69,18 @@ describe.each`
${'query'} | ${'getQuery'} | ${color.green(200)}
${'query'} | ${'getError'} | ${color.yellow(400)}
${'mutation'} | ${'getMutation'} | ${color.green(200)}
`(
'$type $name',
({
type,
name,
status,
}: {
type: string;
name: string;
status: string;
}) => {
it('should log the call', async () => {
await gqlPromise(baseUrl, {
query: `${type} ${name}{ ${name}{ hello }}`,
});
const logObject = logSpy.mock.calls[0][0];
const requestId = logSpy.mock.calls[0][2];
expect(logObject).toBeALogObject(
type,
'/graphql',
'HTTP/1.1',
status,
);
expect(typeof requestId).toBe('string');
expect(requestId).toHaveLength(16);
`('$type $name', ({ type, name, status }: { type: string; name: string; status: string }) => {
it('should log the call', async () => {
await gqlPromise(baseUrl, {
query: `${type} ${name}{ ${name}{ hello }}`,
});
},
);
const logObject = logSpy.mock.calls[0][0];
const requestId = logSpy.mock.calls[0][2];
expect(logObject).toBeALogObject(type, '/graphql', 'HTTP/1.1', status);
expect(typeof requestId).toBe('string');
expect(requestId).toHaveLength(16);
});
});
describe('getSkip', () => {
it('should make the call but skip the log', async () => {
await gqlPromise(baseUrl, {
Expand Down
10 changes: 1 addition & 9 deletions integration/test/grpc.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,7 @@ describe('GrpcParser', () => {
${'/error'} | ${color.red(500)} | ${'SayError'}
`(
'$url call',
async ({
url,
status,
endpoint,
}: {
url: string;
status: string;
endpoint: string;
}) => {
async ({ url, status, endpoint }: { url: string; status: string; endpoint: string }) => {
await httpPromise(baseUrl + url);
expect(logSpy).toBeCalledTimes(1);
const logObject = logSpy.mock.calls[0][0];
Expand Down
12 changes: 2 additions & 10 deletions integration/test/http.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import { HttpServer, INestApplication } from '@nestjs/common';
import { ExpressAdapter } from '@nestjs/platform-express';
import { FastifyAdapter } from '@nestjs/platform-fastify';
import {
AbstractInterceptorService,
OgmaInterceptor,
Type,
} from '@ogma/nestjs-module';
import { AbstractInterceptorService, OgmaInterceptor, Type } from '@ogma/nestjs-module';
import { color } from '@ogma/logger';
import { ExpressParser } from '@ogma/platform-express';
import { FastifyParser } from '@ogma/platform-fastify';
Expand Down Expand Up @@ -66,11 +62,7 @@ describe.each`
logSpy.mockClear();
});

function expectLogObject(
method: string,
endpoint: string,
status: string,
) {
function expectLogObject(method: string, endpoint: string, status: string) {
const logObject = logSpy.mock.calls[0][0];
expect(logObject).toBeALogObject(method, endpoint, 'HTTP/1.1', status);
expect(logSpy).toHaveBeenCalledTimes(1);
Expand Down
37 changes: 37 additions & 0 deletions integration/test/nested-module.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { createProviderToken, OgmaService } from '@ogma/nestjs-module';
import { NestedModule } from '../src/nested-module/app.module';
import { AppService } from '../src/nested-module/app.service';
import { httpPromise } from './utils';

describe('NestedModule', () => {
let app: INestApplication;
let ogmaService: OgmaService;

beforeAll(async () => {
const modRef = await Test.createTestingModule({
imports: [NestedModule],
}).compile();
app = modRef.createNestApplication();
ogmaService = modRef.get(createProviderToken(AppService.name));
await app.listen(0);
});

afterAll(async () => {
await app.close();
});

describe('call endpoint', () => {
let appUrl: string;
beforeAll(async () => {
appUrl = await app.getUrl();
});
it('should instantiate and call /', async () => {
const spy = jest.spyOn(ogmaService, 'log');
await httpPromise(appUrl);
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith('Hello NestedModule');
});
});
});
13 changes: 2 additions & 11 deletions integration/test/rpc.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,7 @@ import {
} from '@nestjs/microservices';
import { Test } from '@nestjs/testing';
import { color } from '@ogma/logger';
import {
AbstractInterceptorService,
OgmaInterceptor,
Type,
} from '@ogma/nestjs-module';
import { AbstractInterceptorService, OgmaInterceptor, Type } from '@ogma/nestjs-module';
import { MqttParser } from '@ogma/platform-mqtt';
import { NatsParser } from '@ogma/platform-nats';
import { RabbitMqParser } from '@ogma/platform-rabbitmq';
Expand Down Expand Up @@ -136,12 +132,7 @@ describe.each`
const logObject = logSpy.mock.calls[0][0];
const requestId = logSpy.mock.calls[0][2];

expect(logObject).toBeALogObject(
server,
JSON.stringify(endpoint),
protocol,
status,
);
expect(logObject).toBeALogObject(server, JSON.stringify(endpoint), protocol, status);
expect(typeof requestId).toBe('string');
expect(requestId).toHaveLength(16);
},
Expand Down
10 changes: 4 additions & 6 deletions integration/test/utils/getInterceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,14 @@ import { INestApplication, INestMicroservice } from '@nestjs/common';
import { OgmaInterceptor } from '@ogma/nestjs-module';

// just trust me... I hate this...
export function getInterceptor(
app: INestApplication | INestMicroservice,
): OgmaInterceptor {
export function getInterceptor(app: INestApplication | INestMicroservice): OgmaInterceptor {
return app.get<OgmaInterceptor>(
Array.from((app as any).container.getModules().values())
.filter((module: any) => module.metatype.name === 'RootTestModule')
.map((module: any) => {
return Array.from<string>(
module.providers.keys(),
).filter((prov: string) => prov.includes('APP_INTERCEPTOR'))[0];
return Array.from<string>(module.providers.keys()).filter((prov: string) =>
prov.includes('APP_INTERCEPTOR'),
)[0];
})[0],
);
}
5 changes: 1 addition & 4 deletions integration/test/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ export * from './gql-promise';
export * from './http-promise';
export * from './ws-promise';
export const hello = JSON.stringify({ hello: 'world' });
export const serviceOptionsFactory = (
app: string,
json = false,
): OgmaServiceOptions => {
export const serviceOptionsFactory = (app: string, json = false): OgmaServiceOptions => {
return { application: app, stream, json };
};
Loading

0 comments on commit 8599d35

Please sign in to comment.