Improve types and error support in Logger.error (#38160)

This commit is contained in:
Sam Seay 2023-05-09 19:57:50 +12:00 committed by GitHub
parent 329fcd1bc3
commit bd7590dc59
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 84 additions and 3 deletions

View File

@ -0,0 +1,71 @@
jest.spyOn( global.console, 'error' ).mockImplementation( () => {} );
// @ts-expect-error -- We're mocking process exit, it has never return type!
jest.spyOn( global.process, 'exit' ).mockImplementation( () => {} );
/**
* External dependencies
*/
import chalk from 'chalk';
/**
* Internal dependencies
*/
import { Logger } from '../logger';
describe( 'Logger', () => {
afterEach( () => {
jest.resetAllMocks();
} );
describe( 'error', () => {
process.env.LOGGER_LEVEL = 'error';
it( 'should log a message for string messages', () => {
const message = 'test message';
Logger.error( message );
expect( global.console.error ).toHaveBeenCalledWith(
chalk.red( message )
);
} );
it( 'should log a message for errors', () => {
const error = new Error( 'test error' );
Logger.error( error );
expect( global.console.error ).toHaveBeenCalledWith(
chalk.red( error.message )
);
} );
it( 'should json stringify for unknown types', () => {
Logger.error( { foo: 'bar' } );
expect( global.console.error ).toHaveBeenCalledWith(
chalk.red( JSON.stringify( { foo: 'bar' }, null, 2 ) )
);
} );
it( 'should call process.exit by default', () => {
Logger.error( 'test message' );
expect( global.process.exit ).toHaveBeenCalledWith( 1 );
} );
it( 'should not call process.exit when failOnErr is false', () => {
Logger.error( 'test message', false );
expect( global.process.exit ).not.toHaveBeenCalled();
} );
it( 'should not log errors if the Logger is in silent mode', () => {
process.env.LOGGER_LEVEL = 'silent';
Logger.error( 'test message' );
expect( global.console.error ).not.toHaveBeenCalled();
} );
} );
} );

View File

@ -25,12 +25,22 @@ export class Logger {
] as number;
}
static error( message: string ) {
static error( err: unknown, failOnErr = true ) {
if ( Logger.loggingLevel >= LOGGING_LEVELS.error ) {
error( chalk.red( message ) );
if ( err instanceof Error ) {
error( chalk.red( err.message ) );
} else if ( typeof err === 'string' ) {
error( chalk.red( err ) );
} else {
// Best effort to log the error when we don't know the type.
error( chalk.red( JSON.stringify( err, null, 2 ) ) );
}
if ( failOnErr ) {
process.exit( 1 );
}
}
}
static warn( message: string ) {
if ( Logger.loggingLevel >= LOGGING_LEVELS.warn ) {