Skip to content

Commit

Permalink
Merge pull request #93 from monstar-lab-oss/sivan/logger-service-final
Browse files Browse the repository at this point in the history
feat: logger service funtions
  • Loading branch information
yashmurty authored Mar 9, 2021
2 parents 5f6de23 + 7b8f88b commit 6703cf8
Show file tree
Hide file tree
Showing 18 changed files with 74 additions and 89 deletions.
2 changes: 1 addition & 1 deletion src/app.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { RequestContext } from './shared/request-context/request-context.dto';

describe('AppController', () => {
let moduleRef: TestingModule;
const mockedLogger = { setContext: jest.fn(), logWithContext: jest.fn() };
const mockedLogger = { setContext: jest.fn(), log: jest.fn() };

beforeEach(async () => {
moduleRef = await Test.createTestingModule({
Expand Down
2 changes: 1 addition & 1 deletion src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export class AppController {

@Get()
getHello(@ReqContext() ctx: RequestContext): string {
this.logger.logWithContext(ctx, 'Hello world from App controller');
this.logger.log(ctx, 'Hello world from App controller');

return this.appService.getHello(ctx);
}
Expand Down
2 changes: 1 addition & 1 deletion src/app.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class AppService {
}

getHello(ctx: RequestContext): string {
this.logger.logWithContext(ctx, 'Hello world from App service');
this.logger.log(ctx, 'Hello world from App service');

return 'Hello World!';
}
Expand Down
2 changes: 1 addition & 1 deletion src/auth/controllers/auth.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ describe('AuthController', () => {
refreshToken: jest.fn(),
};

const mockedLogger = { setContext: jest.fn(), logWithContext: jest.fn() };
const mockedLogger = { setContext: jest.fn(), log: jest.fn() };

beforeEach(async () => {
moduleRef = await Test.createTestingModule({
Expand Down
4 changes: 2 additions & 2 deletions src/auth/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export class AuthController {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@Body() credential: LoginInput,
): BaseApiResponse<AuthTokenOutput> {
this.logger.logWithContext(ctx, `${this.login.name} was called`);
this.logger.log(ctx, `${this.login.name} was called`);

const authToken = this.authService.login(ctx);
return { data: authToken, meta: {} };
Expand Down Expand Up @@ -98,7 +98,7 @@ export class AuthController {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@Body() credential: RefreshTokenInput,
): Promise<BaseApiResponse<AuthTokenOutput>> {
this.logger.logWithContext(ctx, `${this.refreshToken.name} was called`);
this.logger.log(ctx, `${this.refreshToken.name} was called`);

const authToken = await this.authService.refreshToken(ctx);
return { data: authToken, meta: {} };
Expand Down
2 changes: 1 addition & 1 deletion src/auth/services/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ describe('AuthService', () => {

const mockedConfigService = { get: jest.fn() };

const mockedLogger = { setContext: jest.fn(), logWithContext: jest.fn() };
const mockedLogger = { setContext: jest.fn(), log: jest.fn() };

beforeEach(async () => {
const moduleRef: TestingModule = await Test.createTestingModule({
Expand Down
10 changes: 5 additions & 5 deletions src/auth/services/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class AuthService {
username: string,
pass: string,
): Promise<UserAccessTokenClaims> {
this.logger.logWithContext(ctx, `${this.validateUser.name} was called`);
this.logger.log(ctx, `${this.validateUser.name} was called`);

// The userService will throw Unauthorized in case of invalid username/password.
const user = await this.userService.validateUsernamePassword(
Expand All @@ -49,7 +49,7 @@ export class AuthService {
}

login(ctx: RequestContext): AuthTokenOutput {
this.logger.logWithContext(ctx, `${this.login.name} was called`);
this.logger.log(ctx, `${this.login.name} was called`);

return this.getAuthToken(ctx, ctx.user);
}
Expand All @@ -58,7 +58,7 @@ export class AuthService {
ctx: RequestContext,
input: RegisterInput,
): Promise<RegisterOutput> {
this.logger.logWithContext(ctx, `${this.register.name} was called`);
this.logger.log(ctx, `${this.register.name} was called`);

// TODO : Setting default role as USER here. Will add option to change this later via ADMIN users.
input.roles = [ROLE.USER];
Expand All @@ -71,7 +71,7 @@ export class AuthService {
}

async refreshToken(ctx: RequestContext): Promise<AuthTokenOutput> {
this.logger.logWithContext(ctx, `${this.refreshToken.name} was called`);
this.logger.log(ctx, `${this.refreshToken.name} was called`);

const user = await this.userService.findById(ctx, ctx.user.id);
if (!user) {
Expand All @@ -85,7 +85,7 @@ export class AuthService {
ctx: RequestContext,
user: UserAccessTokenClaims | UserOutput,
): AuthTokenOutput {
this.logger.logWithContext(ctx, `${this.getAuthToken.name} was called`);
this.logger.log(ctx, `${this.getAuthToken.name} was called`);

const subject = { sub: user.id };
const payload = {
Expand Down
2 changes: 1 addition & 1 deletion src/auth/strategies/local.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class LocalStrategy extends PassportStrategy(Strategy, STRATEGY_LOCAL) {
): Promise<UserAccessTokenClaims> {
const ctx = createRequestContext(request);

this.logger.logWithContext(ctx, `${this.validate.name} was called`);
this.logger.log(ctx, `${this.validate.name} was called`);

const user = await this.authService.validateUser(ctx, username, password);
// Passport automatically creates a user object, based on the value we return from the validate() method,
Expand Down
3 changes: 0 additions & 3 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { ConfigService } from '@nestjs/config';

import { AppModule } from './app.module';

import { AppLogger } from './shared/logger/logger.service';
import { UserService } from './user/services/user.service';
import { ROLE } from './auth/constants/role.constant';
import { CreateUserInput } from './user/dtos/user-create-input.dto';
Expand All @@ -12,8 +11,6 @@ import { RequestContext } from './shared/request-context/request-context.dto';
async function bootstrap() {
const app = await NestFactory.createApplicationContext(AppModule);

app.useLogger(new AppLogger());

const configService = app.get(ConfigService);
const defaultAdminUserPassword = configService.get<string>(
'defaultAdminUserPassword',
Expand Down
2 changes: 0 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@ import { ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

import { AppModule } from './app.module';
import { AppLogger } from './shared/logger/logger.service';
import { RequestIdMiddleware } from './shared/middlewares/request-id/request-id.middleware';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api/v1');

app.useLogger(new AppLogger());
app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));
app.use(RequestIdMiddleware);
app.enableCors();
Expand Down
1 change: 0 additions & 1 deletion src/shared/filters/all-exceptions.filter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ describe('AllExceptionsFilter', () => {
const mockedLogger = {
warn: jest.fn().mockReturnThis(),
setContext: jest.fn().mockReturnThis(),
warnWithContext: jest.fn().mockReturnThis(),
};
let filter: AllExceptionsFilter<any>;

Expand Down
2 changes: 1 addition & 1 deletion src/shared/filters/all-exceptions.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export class AllExceptionsFilter<T> implements ExceptionFilter {
requestId,
timestamp,
};
this.logger.warnWithContext(requestContext, error.message, {
this.logger.warn(requestContext, error.message, {
error,
stack,
});
Expand Down
2 changes: 1 addition & 1 deletion src/shared/interceptors/logging.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class LoggingInterceptor implements NestInterceptor {

const resData = { method, statusCode, responseTime };

this.appLogger.logWithContext(ctx, 'Request completed', { resData });
this.appLogger.log(ctx, 'Request completed', { resData });
}),
);
}
Expand Down
79 changes: 38 additions & 41 deletions src/shared/logger/logger.service.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Injectable, LoggerService, Scope } from '@nestjs/common';
import { Injectable, Scope } from '@nestjs/common';
import { createLogger, Logger, transports } from 'winston';
import { RequestContext } from '../request-context/request-context.dto';

@Injectable({ scope: Scope.TRANSIENT })
export class AppLogger implements LoggerService {
export class AppLogger {
private context?: string;
private logger: Logger;

Expand All @@ -17,53 +17,49 @@ export class AppLogger implements LoggerService {
});
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
log(message: any, context?: string): Logger {
return this.logger.info(message, {
context: context || this.context,
});
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
error(message: any, trace?: string, context?: string): Logger {
return this.logger.error(message, {
trace,
context: context || this.context,
});
}
error(
ctx: RequestContext,
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
message: string,
meta?: Record<string, any>,
): Logger {
const timestamp = new Date().toISOString();

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
warn(message: any, context?: string): Logger {
return this.logger.warn(message, {
context: context || this.context,
return this.logger.error({
message,
contextName: this.context,
ctx,
timestamp,
...meta,
});
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
debug(message: any, context?: string): Logger {
return this.logger.debug(message, {
context: context || this.context,
});
}
warn(
ctx: RequestContext,
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
message: string,
meta?: Record<string, any>,
): Logger {
const timestamp = new Date().toISOString();

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
verbose(message: any, context?: string): Logger {
return this.logger.verbose(message, {
context: context || this.context,
return this.logger.warn({
message,
contextName: this.context,
ctx,
timestamp,
...meta,
});
}

// TODO : This is a temporary function, it will be renamed to `log` once we update it across
// all controllers, services, etc.
logWithContext(
debug(
ctx: RequestContext,
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
message: any,
message: string,
meta?: Record<string, any>,
): Logger {
const timestamp = new Date().toISOString();

return this.logger.info({
return this.logger.debug({
message,
contextName: this.context,
ctx,
Expand All @@ -72,15 +68,16 @@ export class AppLogger implements LoggerService {
});
}

warnWithContext(
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
verbose(
ctx: RequestContext,
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
message: any,
message: string,
meta?: Record<string, any>,
): Logger {
const timestamp = new Date().toISOString();

return this.logger.warn({
return this.logger.verbose({
message,
contextName: this.context,
ctx,
Expand All @@ -89,15 +86,15 @@ export class AppLogger implements LoggerService {
});
}

errorWithContext(
log(
ctx: RequestContext,
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
message: any,
message: string,
meta?: Record<string, any>,
): Logger {
const timestamp = new Date().toISOString();

return this.logger.error({
return this.logger.info({
message,
contextName: this.context,
ctx,
Expand Down
2 changes: 1 addition & 1 deletion src/user/controllers/user.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ describe('UserController', () => {
updateUser: jest.fn(),
};

const mockedLogger = { setContext: jest.fn(), logWithContext: jest.fn() };
const mockedLogger = { setContext: jest.fn(), log: jest.fn() };

beforeEach(async () => {
const moduleRef: TestingModule = await Test.createTestingModule({
Expand Down
8 changes: 4 additions & 4 deletions src/user/controllers/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export class UserController {
async getMyProfile(
@ReqContext() ctx: RequestContext,
): Promise<BaseApiResponse<UserOutput>> {
this.logger.logWithContext(ctx, `${this.getMyProfile.name} was called`);
this.logger.log(ctx, `${this.getMyProfile.name} was called`);

const user = await this.userService.findById(ctx, ctx.user.id);
return { data: user, meta: {} };
Expand All @@ -81,7 +81,7 @@ export class UserController {
@ReqContext() ctx: RequestContext,
@Query() query: PaginationParamsDto,
): Promise<BaseApiResponse<UserOutput[]>> {
this.logger.logWithContext(ctx, `${this.getUsers.name} was called`);
this.logger.log(ctx, `${this.getUsers.name} was called`);

const { users, count } = await this.userService.getUsers(
ctx,
Expand Down Expand Up @@ -111,7 +111,7 @@ export class UserController {
@ReqContext() ctx: RequestContext,
@Param('id') id: number,
): Promise<BaseApiResponse<UserOutput>> {
this.logger.logWithContext(ctx, `${this.getUser.name} was called`);
this.logger.log(ctx, `${this.getUser.name} was called`);

const user = await this.userService.getUserById(ctx, id);
return { data: user, meta: {} };
Expand All @@ -137,7 +137,7 @@ export class UserController {
@Param('id') userId: number,
@Body() input: UpdateUserInput,
): Promise<BaseApiResponse<UserOutput>> {
this.logger.logWithContext(ctx, `${this.updateUser.name} was called`);
this.logger.log(ctx, `${this.updateUser.name} was called`);

const user = await this.userService.updateUser(ctx, userId, input);
return { data: user, meta: {} };
Expand Down
2 changes: 1 addition & 1 deletion src/user/services/user.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe('UserService', () => {
roles: [ROLE.USER],
};

const mockedLogger = { setContext: jest.fn(), logWithContext: jest.fn() };
const mockedLogger = { setContext: jest.fn(), log: jest.fn() };

beforeEach(async () => {
const moduleRef: TestingModule = await Test.createTestingModule({
Expand Down
Loading

0 comments on commit 6703cf8

Please sign in to comment.