@nestjs/common#Logger TypeScript Examples

The following examples show how to use @nestjs/common#Logger. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: project-import-util.ts    From barista with Apache License 2.0 7 votes vote down vote up
export async function projectFromApprovedRecord(record: any, tag?: string) {
  const logger = new Logger('projectFromApprovedRecord');

  try {
    const project = new Project();
    project.wasImported = true;
    project.importMetaData = record;

    project.name = record.applicationName || 'NO NAME';
    project.userId = record.applicationOwnerMsid;
    project.projectStatus = { code: 'new' } as ProjectStatusType;
    project.outputFormat = { code: 'json' } as OutputFormatType;
    project.outputEmail = record.applicationOwnerEmail;
    project.owner = record.applicationOwnerEmail;

    project.description = record.applicationDesc;

    project.developmentType = { code: 'organization' } as ProjectDevelopmentType;

    // Get deployment type
    project.deploymentType = await deploymentTypeFromImportString(record.applicationDeployment);

    project.packageManager = { code: 'none' } as PackageManager;

    project.globalLicenseException = true;
    project.globalSecurityException = true;

    if (tag) {
      project.tag = tag;
    }

    return project;
  } catch (e) {
    // tslint:disable:no-console
    logger.error(JSON.stringify(record, null, 2));
    logger.error(JSON.stringify(e, null, 2));
    // tslint:enable:no-console
  }
}
Example #2
Source File: utils.ts    From rewind with MIT License 7 votes vote down vote up
/**
 * Checks certain files to see if Rewind can be booted without any problems with the given `osuFolderPath`.
 * @param osuFolderPath the folder path to check the files in
 */
export async function osuFolderSanityCheck(osuFolderPath: string) {
  try {
    await Promise.all(filesToCheck.map((f) => access(join(osuFolderPath, f), constants.R_OK)));
  } catch (err) {
    Logger.log(err);
    return false;
  }
  return true;
}
Example #3
Source File: gcloud-storage-files.interceptor.ts    From nestjs-gcloud-storage with MIT License 6 votes vote down vote up
export function GCloudStorageFilesInterceptor(
  fieldName: string,
  localOptions?: MulterOptions,
  gcloudStorageOptions?: Partial<GCloudStoragePerRequestOptions>,
): Type<NestInterceptor> {
  @Injectable()
  class MixinInterceptor implements NestInterceptor {
    public interceptor: NestInterceptor;

    constructor(private readonly gcloudStorage: GCloudStorageService) {
      this.interceptor = new (FilesInterceptor(fieldName, 20, localOptions))();
    }

    async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
      (await this.interceptor.intercept(context, next)) as Observable<any>;

      const request = context.switchToHttp().getRequest();

      const files = request[fieldName];

      if (!files.length) {
        Logger.error(
          'GCloudStorageFilesInterceptor',
          `Can not intercept field "${fieldName}". Did you specify the correct field name in @GCloudStorageFilesInterceptor('${fieldName}')?`,
        );
        return;
      }

      for (const file of files) file.storageUrl = await this.gcloudStorage.upload(file, gcloudStorageOptions);

      return next.handle();
    }
  }

  const Interceptor = mixin(MixinInterceptor);
  return Interceptor as Type<NestInterceptor>;
}
Example #4
Source File: consul.service.ts    From nestjs-consul with MIT License 6 votes vote down vote up
private async getKeyFromConsul(k: IConsulKeys) {
		try {
			const { data } = await this.httpService
				.get<IConsulResponse[]>(`${this.consulURL}${String(k.key)}`, {
					headers: {
						'X-Consul-Token': this.token,
					},
				}).toPromise();
			return data;
		} catch (e) {
			const msg = `Cannot find key ${String(k.key)}`;
			if (k.required) {
				throw new Error(msg)
			}
			Logger.warn(msg);
			return null;
		}
	}
Example #5
Source File: fcm.module.ts    From nestjs-fcm with MIT License 6 votes vote down vote up
static forRoot(options: FcmOptions): DynamicModule {
    const optionsProvider: ValueProvider = {
      provide: FCM_OPTIONS,
      useValue: options,
    };
    const logger = options.logger ? options.logger : new Logger('FcmService');
    return {
      module: FcmModule,
      providers: [
        { provide: Logger, useValue: logger },
        FcmService,
        optionsProvider,
      ],
      exports: [FcmService],
    };
  }
Example #6
Source File: convert-xml-to-json-object.ts    From barista with Apache License 2.0 6 votes vote down vote up
export function convertXmlToJsonObject(xml: string) {
  return new Promise<any>((resolve, reject) => {
    const logger = new Logger('ConvertXmlToJsonObject');
    try {
      const parser = new Parser({ explicitArray: false });
      parser.parseString(xml, (err, result) => {
        if (err) {
          reject(err);
        } else if (result) {
          resolve(result);
        } else {
          const message = `convertXmlToJsonObject() [No err or result returned]\n[${xml}}]`;
          this.logger.error(message);
          reject({ message });
        }
      });
    } catch (error) {
      this.logger.error(`convertXmlToJsonObject() error: ${error}\n[${xml}}]`);
      reject(error);
    }
  });
}
Example #7
Source File: default-event-mapper.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
defaultEventMapper = (
  allEvents: ReadEventBusConfigType['allowedEvents'],
) => {
  const logger = new Logger('Default Event Mapper');
  return ((data, options: ReadEventOptionsType) => {
    const className = `${options.eventType}`;
    if (allEvents[className]) {
      logger.log(
        `Build ${className} received from stream ${options.eventStreamId} with id ${options.eventId} and number ${options.eventNumber}`,
      );
      return new allEvents[className](data, options);
    }
    return null;
  }) as ReadEventBusConfigType['eventMapper'];
}
Example #8
Source File: user.repository.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
constructor(
    @InjectRepository(UserOrmEntity)
    private readonly userRepository: Repository<UserOrmEntity>,
  ) {
    super(
      userRepository,
      new UserOrmMapper(UserEntity, UserOrmEntity),
      new Logger('UserRepository'),
    );
  }
Example #9
Source File: aws-creds.service.ts    From whispr with MIT License 6 votes vote down vote up
public async authenticate(): Promise<void> {
    const authenticationData = {
      Username: this.configService.get('COGNITO_ADMIN_USER'),
      Password: this.configService.get('COGNITO_ADMIN_PW'),
    };
    const authenticationDetails = new AuthenticationDetails(authenticationData);
    const poolData = {
      UserPoolId: this.configService.get('COGNITO_USER_POOL_ID'), // Your user pool id here
      ClientId: this.configService.get('COGNITO_CLIENT_ID_ADMIN'), // Your client id here
    };
    const userPool = new CognitoUserPool(poolData);
    const userData = {
      Username: this.configService.get('COGNITO_ADMIN_USER'),
      Pool: userPool,
    };
    const cognitoUser = new CognitoUser(userData);
    const authDetails = await AWSCredsService.getCognitoUserSession(cognitoUser, authenticationDetails);
    this.aws.config.region = this.configService.get('COGNITO_REGION');
    const cognitoConfig = {
      IdentityPoolId: this.configService.get('COGNITO_IDENTITY_POOL_ID'), // your identity pool id here
      Logins: {},
    };
    cognitoConfig.Logins[`cognito-idp.eu-west-1.amazonaws.com/${this.configService.get('COGNITO_USER_POOL_ID')}`] = authDetails
      .getIdToken()
      .getJwtToken();
    const credentials = new AWS.CognitoIdentityCredentials(cognitoConfig);
    this.aws.config.credentials = credentials;

    return new Promise((resolve, reject) => {
      credentials.refresh(async (error) => {
        if (error) {
          Logger.error(error);
          reject(error);
        } else {
          resolve();
        }
      });
    });
  }
Example #10
Source File: account.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
// private readonly logger = new Logger('account');

  constructor(
    private readonly accountService: AccountService,
    @Inject(UserService) private readonly userService: UserService,
    @Inject(AuthService) private readonly authService: AuthService,
    @Inject(ApplicationService) private readonly applicationService: ApplicationService,
    @Inject(MailerService) private readonly mailerService: MailerService,
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger = new Logger('account'),
  ) {}
Example #11
Source File: main.ts    From svvs with MIT License 6 votes vote down vote up
/**
 * Bootstrap backend-api app
 */
async function bootstrap() {
  const app = await NestFactory.create(AppModule)
  const globalPrefix = 'api'
  app.setGlobalPrefix(globalPrefix)
  const port = process.env.API_PORT || 3333
  await app.listen(port, () => {
    Logger.log('Listening at http://localhost:' + port + '/' + globalPrefix)
  })
}
Example #12
Source File: upload-sonde-data.ts    From aqualink-app with MIT License 6 votes vote down vote up
async function run() {
  // Initialize Nest logger
  const logger = new Logger('ParseSondeData');
  // Extract command line arguments
  const { f: filePath, s: siteId, p: surveyPointId, t: sourceType } = argv;

  logger.log(
    `Script params: filePath: ${filePath}, siteId/surveyPointId: ${siteId}/${surveyPointId}, sourceType: ${sourceType}`,
  );

  // Initialize typeorm connection
  const config = configService.getTypeOrmConfig() as ConnectionOptions;
  const connection = await createConnection(config);

  logger.log('Uploading sonde data');
  await uploadTimeSeriesData(
    filePath,
    last(filePath.split('/')) || '',
    siteId,
    surveyPointId,
    sourceType as SourceType,
    // Fetch all needed repositories
    {
      siteRepository: connection.getRepository(Site),
      surveyPointRepository: connection.getRepository(SiteSurveyPoint),
      timeSeriesRepository: connection.getRepository(TimeSeries),
      sourcesRepository: connection.getRepository(Sources),
      dataUploadsRepository: connection.getRepository(DataUploads),
    },
  );

  logger.log('Finished uploading sonde data');
}
Example #13
Source File: load-module.ts    From google-recaptcha with MIT License 6 votes vote down vote up
export function loadModule(moduleName: string, logError = false): any {
    try {
        return require(moduleName);
    } catch (e) {
        if (logError) {
            Logger.error(`Module '${moduleName}' not found. \nPotential solution npm i  ${moduleName}`);
        }
        throw e;
    }
}
Example #14
Source File: app.controller.ts    From nestjs-jaeger-tracing with MIT License 6 votes vote down vote up
@UseInterceptors(TracingInterceptor)
  @MessagePattern({ cmd: 'echoMessage' })
  echoMessage(
    @Tracing() tracing: TracingData,
    @Payload() message: string,
  ): string {
    Logger.log({ echoMessage: tracing });
    return message;
  }
Example #15
Source File: auth.guard.ts    From nest-keycloak-connect with MIT License 6 votes vote down vote up
constructor(
    @Inject(KEYCLOAK_INSTANCE)
    private singleTenant: KeycloakConnect.Keycloak,
    @Inject(KEYCLOAK_CONNECT_OPTIONS)
    private keycloakOpts: KeycloakConnectConfig,
    @Inject(KEYCLOAK_LOGGER)
    private logger: Logger,
    private multiTenant: KeycloakMultiTenantService,
    private readonly reflector: Reflector,
  ) {}
Example #16
Source File: http-exception.filter.ts    From nest-js-products-api with MIT License 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-explicit-any
  public isBusinessException(exception: Error): any {
    if (exception instanceof PriceProductLessZeroException) {
      return {
        message: exception.message,
        status: 400,
      };
    }
    Logger.log(exception.stack);
    return {
      message: 'unknown',
      status: 500,
    };
  }
Example #17
Source File: dynamoose-core.module.ts    From nestjs-dynamoose with MIT License 6 votes vote down vote up
function initialization(options: DynamooseModuleOptions) {
  if (options.aws) {
    aws.sdk.config.update(options.aws);
  }
  if (options.local) {
    if (typeof options.local === 'boolean') {
      aws.ddb.local();
    } else {
      aws.ddb.local(options.local);
    }
  }
  if (options.ddb) {
    aws.ddb.set(options.ddb);
  }
  if (options.model) {
    model.defaults.set(options.model);
  }
  if (options.logger) {
    logger.providers.add(
      new LoggerProvider(
        typeof options.logger === 'boolean'
          ? new Logger(DynamooseModule.name)
          : options.logger,
      ),
    );
  }
}
Example #18
Source File: main.ts    From emutypekov with GNU General Public License v3.0 6 votes vote down vote up
async function bootstrap(logger: Logger) {
  logger.log(SystemService.Watermark);

  const app = await NestFactory.create<NestExpressApplication>(CoreModule);

  app.useGlobalInterceptors(new SystemInterceptor());
  app.useStaticAssets(join(__dirname, '..', 'web', 'static'));
  app.setBaseViewsDir(join(__dirname, '..', 'web', 'views'));
  app.setViewEngine('hbs');
  app.disable('etag');

  if (DODEBUG) {
    DebugModule.graph(app);
  }

  const common = app.select(CoreModule).get(CommonService);

  try {
    await app.listen(common.serverConfig.port, common.serverConfig.address);
    logger.log(
      `${SystemService.Server} is listening on ${common.serverConfig.address}:${common.serverConfig.port}.`,
    );
  } catch (e) {
    logger.error(e);
  }
}
Example #19
Source File: client.provider.ts    From nest-mqtt with MIT License 6 votes vote down vote up
export function createClientProvider(): Provider {
  return {
    provide: MQTT_CLIENT_INSTANCE,
    useFactory: (options: MqttModuleOptions, logger: Logger) => {
      const client = connect(options);

      client.on('connect', () => {
        logger.log('MQTT connected');
        // console.log(packet);
      });

      client.on('disconnect', packet => {
        logger.log('MQTT disconnected');
      });

      client.on('error', error => {
      });

      client.on('reconnect', () => {
        logger.log('MQTT reconnecting');
      });

      client.on('close', error => {
        logger.log('MQTT closed');
      });

      client.on('offline', () => {
        logger.log('MQTT offline');
      });

      return client;
    },
    inject: [MQTT_OPTION_PROVIDER, MQTT_LOGGER_PROVIDER],
  };
}
Example #20
Source File: app.module.ts    From 42_checkIn with GNU General Public License v3.0 5 votes vote down vote up
@Module({
  imports: [
    ConfigModule.forRoot({
      load: [configuration],
      isGlobal: true,
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: 'mysql',
        host: configService.get('database.host'),
        port: configService.get('database.port'),
        username: configService.get('database.username'),
        password: configService.get('database.password'),
        database: configService.get('database.name'),
        entities: [join(__dirname, '/**/*.entity.js')],
        synchronize: true,
      }),
    }),
    // ServeStaticModule.forRoot({
    //   rootPath: resolve(__dirname, '../../../client/build'),
    // }),
    TerminusModule,
    UserModule,
    AuthModule,
    CardModule,
    LogModule,
    HealthModule,
    LoggerModule,
    ThrottlerModule.forRoot({
      ttl: 60,
      limit: 20,
    }),
    WaitingModule,
    HttpModule,
    // MailerModule.forRootAsync({
    //   imports: [ConfigModule],
    //   inject: [ConfigService],
    //   useFactory: (configService: ConfigService) => ({
    //     transport: configService.get('mailer.mail'),
    //     defaults: {
    //       from: '"42 출입 시스템" <[email protected]>',
    //     },
    //     template: {
    //       dir: __dirname + '/templates',
    //       adapter: new EjsAdapter(),
    //       options: {
    //         strict: true,
    //       },
    //     },
    //   }),
    // }),
    ScheduleModule.forRoot(),
  ],
  controllers: [AppController, HealthController, WaitingController],
  providers: [
    AppService,
    Logger,
    { provide: APP_GUARD, useClass: TokenThrottlerGuard },
  ],
})
export class AppModule {}
Example #21
Source File: gcloud-storage.service.ts    From nestjs-gcloud-storage with MIT License 5 votes vote down vote up
private readonly logger = new Logger(GCloudStorageService.name);
Example #22
Source File: fcm.service.ts    From nestjs-fcm with MIT License 5 votes vote down vote up
constructor(
    @Inject(FCM_OPTIONS) private fcmOptionsProvider: FcmOptions,
    private readonly logger: Logger,
  ) {}
Example #23
Source File: graphql.factory.ts    From nestjs-mercurius with MIT License 5 votes vote down vote up
private readonly logger = new Logger(GraphQLFactory.name);
Example #24
Source File: main.ts    From nest-nuxt-starter with MIT License 5 votes vote down vote up
log = new Logger('Bootstrap')
Example #25
Source File: config.service.ts    From nest-react with GNU Lesser General Public License v3.0 5 votes vote down vote up
private logger = new Logger(ConfigService.name);
Example #26
Source File: app.service.ts    From barista with Apache License 2.0 5 votes vote down vote up
logger = new Logger('AppService');
Example #27
Source File: write-events-prepublish.service.ts    From nestjs-geteventstore with MIT License 5 votes vote down vote up
private readonly logger = new Logger(this.constructor.name);
Example #28
Source File: unit-of-work.module.ts    From domain-driven-hexagon with MIT License 5 votes vote down vote up
unitOfWorkSingleton = new UnitOfWork(new Logger())
Example #29
Source File: logger.middleware.ts    From whispr with MIT License 5 votes vote down vote up
export function logger(req: Request, _res: Response, next: NextFunction) {
  if (req.headers) {
    Logger.log(headersToString(req.headers));
  }
  next();
}