question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

winston-daily-rotate-file cannot be imported in typescript

See original GitHub issue

I am using typescript and I want to use your main class. Instead I get following error:

/Users/paulowski/.../build/Logger.js:109
    return new DailyRotateFile(Object.assign({
           ^

TypeError: DailyRotateFile is not a constructor

How should I import your package? I have already read some comments but I do not have a clue. Besides: console-logging DailyRotateFile returns this:

{ super_:
   { [Function: TransportStream]
     super_:
      { [Function: Writable] WritableState: [Function: WritableState], super_: [Function] } },
  default:
   { [Function: DailyRotateFile] super_: { [Function: TransportStream] super_: [Function] } } }

Logger.js

import jc from "json-cycle";
import { Format, TransformableInfo, TransformFunction } from "logform";
import * as path from "path";
import * as winston from "winston";
import * as DailyRotateFile from "winston-daily-rotate-file";
import * as Transport from "winston-transport";

type StampedInfo = TransformableInfo & {
    timestamp: string,
};

type LogLevel = "error" | "info" | "warn" | "debug";

export default class Logger {
    public static buildLogger({
        domain,
        parseArgs = true,
        logInConsole = true,
    }: {
        domain: string,
        parseArgs?: boolean,
        logInConsole?: boolean,
    }): winston.Logger {
        const logPath = path.join(__dirname, "..", "logs");

        const errorTransport = Logger.getErrorTransport(logPath);
        const infoTransport = Logger.getInfoTransport(logPath);
        const debugTransport = Logger.getDebugTransport(logPath);

        const transports = [errorTransport, infoTransport, debugTransport];

        if (logInConsole) {
            transports.push(Logger.getConsoleTransport("debug"));
        }

        return winston.createLogger({
            format: Logger.getFormat(domain, parseArgs),
            transports,
        });
    }

    public static assembleLogOutput(
        domain: string,
        parseArgs: boolean,
        info: StampedInfo): string {
        const {
            timestamp, level, message, ...args
        } = info;

        const ts = timestamp.slice(0, 19).replace("T", " ");
        // print out a special prefix when in test mode
        const testPrefix = (process.env.JEST_WORKER_ID === undefined) ? "" : "TEST-MODE";

        return `${testPrefix} [${domain}] [${level}] @ ${ts}: ${message} ${parseArgs ?
            Object.keys(args).length ?
                JSON.stringify(jc.decycle(args), null, 2) :
                "" :
            ""}`;

    }

    public static getFormat(domain: string, parseArgs: boolean = true): Format {
        const extractError = winston.format((info: TransformableInfo) => {
            function unfoldError(error: Error): TransformableInfo {
                return Object.assign({
                    message: info.message,
                    stack: info.stack,
                }, info) as TransformableInfo;
            }

            if (info instanceof Error) { return unfoldError(info); }

            for (const value of info.values()) {
                if (value instanceof Error) {
                    return unfoldError(value);
                }
            }

            return info; // Nothing special? Then, pass it along.
        });

        return winston.format.combine(
            winston.format.timestamp(),
            winston.format.align(),
            extractError(),
            winston.format.printf((info: StampedInfo) => {
                return Logger.assembleLogOutput(domain, parseArgs, info);
            }),
        );
    }
    public static getDebugTransport(logPath: string): Transport {
        return Logger.getFileTransport(logPath, "debug");
    }

    public static getInfoTransport(logPath: string): Transport {
        return Logger.getFileTransport(logPath, "info");
    }

    public static getErrorTransport(logPath: string): Transport {
        return Logger.getFileTransport(logPath, "error");
    }

    public static getFileTransport(logPath: string, level: string, config = {
        datePattern: "HH-DD-MM-YYYY",
        maxFiles: "14d",
        maxSize: "20m",
        zippedArchive: true,
    }) {
        return new DailyRotateFile(Object.assign({
            filename: path.join(logPath, level, `${level}-%DATE%.log`),
            level,
        }, config));
    }

    public static getConsoleTransport(level: LogLevel) {
        return new winston.transports.Console(
            {
                format: winston.format.combine(
                    winston.format.colorize(),
                ),
                level,
            },
        );
    }

    public static isInTestMode(): boolean {
        return process.env.JEST_WORKER_ID !== undefined;
    }

    private winston: winston.Logger;

    constructor(private domain: string, parseArgs: boolean = true) {
        this.winston = Logger.buildLogger({ domain, parseArgs });
    }

    public error(message: string, trace: string) {
        this.log("error", message);

    }

    public warn(message: string) {
        this.log("warn", message);
    }

    public info(message: string) {
        this.log("info", message);
    }

    public log(level: LogLevel, message: string) {
        this.winston.log({ level, message });
    }
}

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:1
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

13reactions
Adekoredaycommented, Apr 19, 2020

These works in es6 in case anyone still has these issues

import * as winston from 'winston';
import 'winston-daily-rotate-file';
7reactions
mattberthercommented, Jan 12, 2019

I think you probably want:

import DailyRotateFile = require("winston-daily-rotate-file");

or

import DailyRotateFile = from "winston-daily-rotate-file";

Not sure on the latter, as I’m not familiar with Typescript. Reopen this issue if one of those don’t work for you.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to import NodeJS winston-daily-rotate-file dependency?
var DailyRotateFile = require('winston-daily-rotate-file');. But when I try to import like below, it is not working. How to resolve it? import * ...
Read more >
winston-daily-rotate-file - npm
A transport for winston which logs to a rotating file each day.. Latest version: 4.7.1, last published: 7 months ago.
Read more >
Using 'winston-daily-rotate-file in TypeScript - Knowledgebase
In TypeScript you need to import the library 'winston-daily-rotate-file' like, so: import 'winston-daily-rotate-file'. import { createLogger ...
Read more >
winston-daily-rotate-file - npm package - Snyk
A transport for winston which logs to a rotating file each day. For more information about how to use this package see README....
Read more >
winstonjs/winston - Gitter
It seems like that would be a pretty basic option, but I can't find it ... But looks like its some problem with...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found