Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: Winston Error not output anything. #2133

Closed
ShaunB-SQ opened this issue May 18, 2022 · 4 comments
Closed

[Bug]: Winston Error not output anything. #2133

ShaunB-SQ opened this issue May 18, 2022 · 4 comments

Comments

@ShaunB-SQ
Copy link

🔎 Search Terms

logger.error not working

The problem

I have a logger in my code like

const winston = require('winston');

const errorStackFormat = winston.format((info) => {
  if (info.level === 'error') {
    console.dir(info, { colors: true, depth: null });
    info.message = `${info.name ? info.name : ''}${info.code ? ` ${info.code}` : ''}${
      info.message ? ` ${info.message}` : ''
    }${info.originalError ? `\n${info.originalError.stack}` : ''}`;
  }
  return info;
});

// eslint-disable-next-line new-cap
const logger = new winston.createLogger({
  level: process.env.LOG_LEVEL || 'debug',
  transports: [
    new winston.transports.Http({
      format: winston.format.combine(winston.format.align(), winston.format.cli()),
    }),
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.errors({ stack: true }),
        errorStackFormat(),
        winston.format.colorize(),
        winston.format.timestamp(),
        winston.format.align(),
        winston.format.simple(),
        winston.format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}`)
      ),
      stderrLevels: ['error'],
      consoleWarnLevels: ['warn'],
    }),
    new winston.transports.File({
      format: winston.format.combine(
        winston.format.errors({ stack: true }),
        errorStackFormat(),
        winston.format.uncolorize(),
        winston.format.json()
      ),
      filename: 'error.log',
      level: 'error',
      maxsize: 1 * 1024 * 1024 * 1024, // 1GB,
      maxFiles: 5,
      tailable: true,
    }),
    new winston.transports.File({
      format: winston.format.combine(
        winston.format.errors({ stack: true }),
        errorStackFormat(),
        winston.format.uncolorize(),
        winston.format.json()
      ),
      filename: 'combined.log',
      maxsize: 1 * 1024 * 1024 * 1024, // 1GB,
      maxFiles: 5,
      tailable: true,
    }),
  ],
});

module.exports = logger;
// https://github.com/winstonjs/winston/blob/HEAD/docs/transports.md

I tried if (info instanceof Error) but that always came back false in my Error Stack Format function.
however when I get a logger.error(error) from anywhere else in the application

`if (info.level === 'error')
the console.dir in here doesn't seem to include ANYTHING, and what I get on the screen is

{
 level: 'error',
 [Symbol(level)]: 'error',
 [Symbol(message)]: '{"level":"error"}'
}

when what I really want out in both the error file and the screen is information on the error and where to find it.

app.use: TypeError: AdjustmentView.findAll(...).map is not a function
    at getAllAdjustments (/usr/src/app/server/src/service/adjustmentService.js:239:35)
    at findAllAdjustments (/usr/src/app/server/life/adjustment/adjustmentController.js:14:31)
    at Layer.handle [as handle_request] (/usr/src/app/server/node_modules/express/lib/router/layer.js:95:5)
    at next (/usr/src/app/server/node_modules/express/lib/router/route.js:144:13)
    at /usr/src/app/server/src/modules/permissionMiddleware.js:12:9
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

I have been through documentation and stack overflows and they told me to use the winston.format.errors({ stack: true }),, which I am already using.

two things"
1.) Don't know why a caught errror or a callback error isn't seen as an instance of an Error when it gets to the logger function I made.

    app.use((err, req, res, next) => {
      console.error('app.use:', err);
      logger.error(err);
      if (res.statusCode === 200) res.status(500);
      res.json({ message: err.message });
      next();
    });

2.) I can't use winston in any way if it won't give me the error info and how to fix it if one occurs.

What version of Winston presents the issue?

3.7.2

What version of Node are you using?

16.14.2

If this worked in a previous version of Winston, which was it?

No response

Minimum Working Example

No response

Additional information

No response

@CAGLADJ
Copy link

CAGLADJ commented Aug 4, 2022

I have something similar happening. I give an instance of Error into the logger:

console.log(error instanceof Error) // This shows true
logger.error(error)

But inside errors.js of the logform library einfo is not an instance of Error:

module.exports = format((einfo, { stack }) => {
  console.log(einfo instanceof Error) // This shows false
  if (einfo instanceof Error) {

I am not sure at what point the inserted Object becomes not an Error instance.

My transports settings:

new transports.DailyRotateFile({
    level: 'error',
    filename: 'core-errors-%DATE%.log',
    dirname: './logs',
    frequency: (config.logging.rotationInterval * 24) + 'h',
    maxFiles: config.logging.deletionInterval + 'd',
    format: format.combine(
        format.errors({ stack: true }),
        format.timestamp({
            format: 'YYYY-MM-DD HH:mm:ss'
        }),
        errorFormat
    )
})

@CAGLADJ
Copy link

CAGLADJ commented Aug 5, 2022

I have found, what my mistake was. You have to add format.errors({ stack:true }) into the format property of the logger and not of the transport. The code below works for me. Maybe it helps you, too.

const logger = createLogger({
    format: format.combine(
        format.errors({ stack:true }),
        format.json()
    ),
    transports: [
      new transports.DailyRotateFile({
        level: 'error',
        filename: 'core-errors-%DATE%.log',
        dirname: './logs',
        frequency: (config.logging.rotationInterval * 24) + 'h',
        maxFiles: config.logging.deletionInterval + 'd',
        format: format.combine(
            format.timestamp({
                format: 'YYYY-MM-DD HH:mm:ss'
            }),
            errorFormat
        )
      })
    ]
})

@e-osuna-g
Copy link

@CAGLADJ for me it only shows the stack when prettyPrint is on, did you had the same issue?

@maverick1872
Copy link
Member

Please verify this with a version >=v3.8.0.

v3.7.2 introduced a major regression with support for logging errors. See here for additional information. This version release was subsequently reverted and we re-released a previous version to minimize impact. As such none of what 3.7.2 introduced is live on a newer version.

As such I'll be closing this issue as a duplicate (regressions in v3.7.2 are being tracked by #2029). If you are successfully able to reproduce this issue with a later version, please do not hesitate to re-open this! 🙇🏻

@maverick1872 maverick1872 closed this as not planned Won't fix, can't repro, duplicate, stale Feb 28, 2023
ImLunaHey added a commit to ImLunaHey/jive that referenced this issue May 4, 2023
ImLunaHey added a commit to ImLunaHey/ticket-genie that referenced this issue May 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants