简体   繁体   中英

How to add custom function to Winston logger in Typescript?

This question is related to Winston Logger but could apply to any other situation. I have the following code:

import winston, {Logger} from 'winston';

interface CustomLogger extends Logger {
  setLoggerContext(userId: string): void;
}

const logger: CustomLogger = winston.createLogger({
  transports: [new winston.transports.Console()],
});

logger.setLoggerContext = (userId: string) => {
  logger.defaultMeta = {userId: userId}
}

export default logger;

However, const logger is red with an error message saying:

Property 'setLoggerContext' is missing in type 'Logger' but required in type 'CustomLogger'.ts(2741)

I want to protect people from putting defaultMeta what they want, and I really need custom function for this, because later we might change winston with something else, so I want a custom context setter.

Simply construct the intersection of the two interfaces at once (TypeScript can't see that you eventually construct something that conforms to the CustomLogger interface, it only considers the const logger: CustomLogger line):

const CustomLoggerMixin = {
  setLoggerContext(userId: string) {
    logger.defaultMeta = {userId: userId};
  }
};

const logger: CustomLogger = Object.assign(
  winston.createLogger({
    transports: [new winston.transports.Console()],
  }),
  CustomLoggerMixin
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM