Typescript - Морган и logger.stream вызывают ошибку lint - PullRequest
0 голосов
/ 13 июня 2018

Я пытаюсь прикрепить Morgan журнал к Winston, используя функцию потокового журнала.Но как только я пытаюсь присоединить logger.stream, когда я использую промежуточное программное обеспечение morgan, он не может получить следующее сообщение:

Argument of type '"combined"' is not assignable to parameter of type 'FormatFn'.

Вот мой код инициализации Winston:

import * as appRoot from 'app-root-path';
import * as winston from 'winston';
import { Logger } from 'winston';
import * as fs from 'fs';
import * as stream from 'stream';

const dirLogs = `${appRoot}/logs`;

// It's call during initialization, we can block the thread
if (!fs.existsSync(dirLogs)) {
  fs.mkdirSync(dirLogs);
}
// define the custom settings for each transport (file, console)
const options = {
  file: {
    level: 'info',
    filename: `${dirLogs}/app.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 5,
    colorize: false,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: false,
    colorize: true,
  },
};

// Keep it simple to focus on the need first
// I think Logger should send logs to a logger service
const logger = new Logger({
  level: 'info',
  transports: [
    new winston.transports.File(options.file),
    new winston.transports.Console(options.console),
  ],
  exitOnError: false, // do not exit on handled exceptions
});

// If I don't use the stream.Duplex, it cause another lint error.
logger.stream = (options?: any) => new stream.Duplex({
  write: function (message: string, encoding: any) {
      logger.info(message.trim());
  }
});

export default logger;

И затем код, с которым я пытаюсь использовать Моргана.

// ... All import
import logger from './logger/index';

// ... Then later the code
this.expressApp.use(morgan('combined', { stream: logger.stream }));

Я не уверен, что понимаю, почему я получил эту ошибку: /

Ответы [ 2 ]

0 голосов
/ 20 февраля 2019

Установите пакет узла Winston с менеджером пакетов узла

Создайте файл logger.ts и добавьте в него следующий код

import { createLogger, format, transports } from 'winston';
const { label, combine, timestamp , prettyPrint } = format;
const logger = createLogger({
 format: combine(
 timestamp(),
 prettyPrint(),
 ),
 transports: [
 new transports.Console(),
 new transports.File({ filename: './error.log' , level: 'error' }),
 new transports.File({ filename: './info.log' , level: 'info' }),
 ],
 exitOnError: false,
});
export default loggerStep 

Подробнее см. В строке ниже введите описание ссылкиздесь

0 голосов
/ 13 июня 2018

Хорошо, я углубился в код и файлы машинописи, чтобы понять, что на самом деле нужно сделать.

Я изменил свое объявление logger.stream с

// If I don't use the stream.Duplex, it cause another lint error.
logger.stream = (options?: any) => new stream.Duplex({
  write: function (message: string, encoding: any) {
      logger.info(message.trim());
  }
});

на

// Don't forget this import
import { Options } from 'morgan';

// And the code
export const morganOption: Options = {
  stream: {
    write: function (message: string) {
        logger.info(message.trim());
    },
  },
};

Затем я импортирую morganOptions и устанавливаю его на morgan

// My import
import { logger, morganOption } from './logger/index';

// ... Then later, the new code
this.expressApp.use(morgan('combined', morganOption));

Надеюсь, это поможет другим :)

...