feat: use nest logger and support log level env var

This commit is contained in:
Kilian Decaderincourt 2021-11-25 15:14:15 +01:00
parent f43c3d886f
commit 3fcd00e9ca
4 changed files with 21 additions and 3 deletions

View File

@ -13,5 +13,7 @@ It can be used with [kiliandeca/excalidraw-fork](https://gitlab.com/kiliandeca/e
| `PORT` | Server listening port | 8080 |
| `GLOBAL_PREFIX` | API global prefix for every routes | `/api/v2` |
| `STORAGE_URI` | [Keyv](https://github.com/jaredwray/keyv) connection string | `""` (in memory) |
| `LOG_LEVEL` | Log level (`debug`, `verbose`, `log`, `warn`, `error`) | `warn` |
Availabe Keyv storage adapter: redis, mongo, postgres and mysql

View File

@ -1,10 +1,21 @@
import { LogLevel } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
function isLogLevel(value: any): value is LogLevel {
return value in ['log', 'error', 'warn', 'debug', 'verbose'];
}
async function bootstrap() {
const logLevel = isLogLevel(process.env.LOG_LEVEL)
? process.env.LOG_LEVEL
: 'debug';
const app = await NestFactory.create(AppModule, {
cors: true,
logger: [logLevel],
});
app.setGlobalPrefix(process.env.GLOBAL_PREFIX ?? '/api/v2');
await app.listen(process.env.PORT ?? 8080);

View File

@ -4,6 +4,7 @@ import {
Get,
Header,
InternalServerErrorException,
Logger,
Param,
Post,
Res,
@ -15,6 +16,7 @@ import { customAlphabet } from 'nanoid';
@Controller()
export class ScenesController {
private readonly logger = new Logger(ScenesController.name);
namespace = StorageNamespace.SCENES;
constructor(private storageService: StorageService) {}
@ -22,6 +24,7 @@ export class ScenesController {
@Header('content-type', 'application/octet-stream')
async findOne(@Param() params, @Res() res: Response): Promise<void> {
const data = await this.storageService.get(params.id, this.namespace);
this.logger.debug(`Get scene ${params.id}`);
const stream = new Readable();
stream.push(data);
@ -41,6 +44,7 @@ export class ScenesController {
}
await this.storageService.set(id, payload, this.namespace);
this.logger.debug(`Created scene ${id}`);
return {
id,

View File

@ -1,14 +1,15 @@
import { Injectable } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';
import * as Keyv from 'keyv';
@Injectable()
export class StorageService {
private readonly logger = new Logger(StorageService.name);
storagesMap = new Map<string, Keyv>();
constructor() {
const uri = process.env[`STORAGE_URI`];
if (!uri) {
console.error(
this.logger.warn(
`STORAGE_URI is undefined, will use non persistant in memory storage`,
);
}
@ -19,7 +20,7 @@ export class StorageService {
namespace,
});
keyv.on('error', (err) =>
console.error(`Connection Error for namespace ${namespace}`, err),
this.logger.error(`Connection Error for namespace ${namespace}`, err),
);
this.storagesMap.set(namespace, keyv);
});