Skip to content
New issue

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

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

Already on GitHub? # to your account

[Bug]: Message property is undefined when throwing an error #2531

Open
Wazbat opened this issue Nov 19, 2024 · 2 comments
Open

[Bug]: Message property is undefined when throwing an error #2531

Wazbat opened this issue Nov 19, 2024 · 2 comments

Comments

@Wazbat
Copy link

Wazbat commented Nov 19, 2024

🔎 Search Terms

uncaughtException,message undefined, message,undefined

The problem

When logging an uncaught exception with winston, the message property is always undefined when using the console transport

What version of Winston presents the issue?

v3.8.1

What version of Node are you using?

v22.3.0

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

No response

Minimum Working Example

const { createLogger, transports, format } = require('winston');

const logger = createLogger({
    transports: [new transports.Console({
        format: format.printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`)
    })],
    level: 'debug'
});

process.on('uncaughtException', (err) => {
    logger.error(err);
});

throw new Error('this text is lost and not shown anywhere');

Additional information

This is my full logger file, which hopefully shows why I'm handling uncaughtExceptions this way

import { createLogger, transports, format } from 'winston';
import { LoggingWinston } from '@google-cloud/logging-winston';

export const getLogger = (application: string, options?: { silent?: boolean}) => {
    const transportsToUse: NonNullable<NonNullable<Parameters<typeof createLogger>[0]>['transports']> = [];
    if (process.env.NODE_ENV === 'production') {
        const loggingWinston = new LoggingWinston({
            redirectToStdout: true,
            useMessageField: false,
            level: 'info',
            serviceContext: {
                service: application,
                version: process.env.VERSION || 'v0.0.0'
            },
            labels: {
                namespace: process.env.NAMESPACE || 'unknown',
                version: process.env.VERSION || 'unknown'
            }
        });
        transportsToUse.push(loggingWinston);
    } else {
        transportsToUse.push(new transports.Console({
            level: 'debug',
            format: format.combine(
                format.colorize(),
                format.timestamp({
                    format: 'YYYY-MM-DD HH:mm:ss'
                }),
                format.errors({ stack: true }),
                format.printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`)
            )
        }));
    }
    const logger = createLogger({
        transports: transportsToUse,
        silent: options?.silent ?? false
    });
    process.on('uncaughtException', (err) => {
        logger.error(err);
        logger.on('finish', () => {
            process.exit(1);
        });
        logger.on('error', (e) => {
            // eslint-disable-next-line no-console
            console.error('Winston error while logging uncaughtException');
            // eslint-disable-next-line no-console
            console.error(e);
            process.exit(1);
        });
        // https://github.com/googleapis/nodejs-logging-winston/issues/502
        logger.end();
    });
    process.on('unhandledRejection', (reason: Error, promise) => {
        logger.error(`unhandledRejection: ${reason?.message || reason}`, {
            error: reason,
            promise
        });
        logger.error(reason);
    });

    return logger;
};

Perhaps I'm just going about this the wrong way?

@MrSuddenJoy
Copy link

MrSuddenJoy commented Feb 10, 2025

Indeed, message property has to be defined.

let message = loggedMessage.Text;

@Oluwatemilorun
Copy link

Oluwatemilorun commented Feb 14, 2025

I am also facing this issue. Basically, no exception is being logged. Even when I have logger.error(new Error('Some error'), The error log does not show up.

I dug in and I saw this getAllInfo method. Extracted it used it with logger.log() like

function getAllInfo(err: Error) {
  return {
    level: 'error',
    error: err,
    message: [
      `${err.message || '(no error message)'}`,
      (err && err.stack) || '  No stack trace',
    ].join('\n'),
    stack: err && err.stack,
    exception: true,
    // date: new Date().toString(),
    process: getProcessInfo(),
    os: getOsInfo(),
    trace: getTrace(err),
  };
}

const logError = (err: Error) => logger.log(getAllInfo(err))

logError(new Error('Some error')) // Nothing is logged

But then I commented out the exception: true line, and it worked - the error log showed with the stack trace.

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

3 participants