Skip to content

Commit

Permalink
feat(logger): added support for custom logger
Browse files Browse the repository at this point in the history
fix #2
  • Loading branch information
grantila committed Mar 3, 2021
1 parent 976f9ff commit 0d1df76
Show file tree
Hide file tree
Showing 8 changed files with 127 additions and 44 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,12 @@ You can also use `npx`:
<head><script src="https://cdn.jsdelivr.net/npm/trace-unhandled@latest/browser.js"></script></head>
```

To specify a custom logger function, use `setTraceUnhandledLogger`:

```ts
window.setTraceUnhandledLogger( msg => { ... } ); // msg is a string
```


## Programatically - API

Expand All @@ -127,6 +133,13 @@ const { register } = require( 'trace-unhandled' );
register( );
```

To specify a custom logger function, use `setLogger`:

```ts
const { setLogger } = require( 'trace-unhandled' );
setLogger( msg => { ... } ); // msg is a string
```


## In unit tests

Expand Down
2 changes: 1 addition & 1 deletion index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@

export { LoggerFunction, setLogger } from './lib/core';
export const register = ( ) => require( './lib/register' );
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ module.exports = {
testEnvironment: "node",
testMatch: ['<rootDir>/test/**/*.spec.js'],
coverageReporters: ["lcov", "text", "html"],
coveragePathIgnorePatterns: [ '/node_modules/', '/test/' ],
};
16 changes: 15 additions & 1 deletion lib/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,20 @@ function mergeErrors( traceError: Error, mainError?: Error )
errorLines.slice( 0, i ).reverse( ).join( "\n" );
}

function defaultLogger( msg: string )
{
console.error( msg );
}

export type LoggerFunction = ( msg: string ) => void;

let loggerFunction: LoggerFunction = defaultLogger;

export function setLogger( loggerFn: LoggerFunction )
{
loggerFunction = loggerFn ?? defaultLogger;
}

export function logger(
reason: Error | undefined,
promise: TraceablePromise< any >,
Expand All @@ -69,7 +83,7 @@ export function logger(

const prefix = pid == null ? '' : `(node:${pid}) `;

console.error(
loggerFunction(
`${prefix}UnhandledPromiseRejectionWarning\n` +
(
!promise.__tracedError
Expand Down
41 changes: 41 additions & 0 deletions test/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const { Finally, Try, delay } = require( 'already' );

module.exports.withConsoleSpy = fn => async ( ) =>
{
const oldError = console.error;
console.error = jest.fn( );
return Try( fn )
.then( ...Finally( ( ) =>
{
console.error = oldError;
} ) );
}

module.exports.triggerUnhandledWarnings =
async function triggerUnhandledWarnings( )
{
await delay( 0 );
global.gc && global.gc( );
await delay( 0 );
}

module.exports.splitLines = function splitLines( lines )
{
return [ ].concat( ...lines.map( line => line.split( "\n" ) ) );
}

module.exports.cutColumn = function cutColumn( line )
{
const m = line.match( /(.*:\d+):\d+\)?$/ );
if ( !m )
return line;
return m[ 1 ];
}

module.exports.cutLocation = function cutLocation( line )
{
const m = line.match( /(.*):\d+:\d+\)?$/ );
if ( !m )
return line;
return m[ 1 ];
}
44 changes: 44 additions & 0 deletions test/logger.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@

const index = require( '../dist/index' );
const {
triggerUnhandledWarnings,
splitLines,
cutColumn,
} = require( './helpers' );


describe( "logger", ( ) =>
{
it( "setLogger", async ( ) =>
{
const logger = jest.fn( );
index.setLogger( logger );
index.register( );

const err = new Error( "foobar" );

new Promise( ( resolve, reject ) =>
{
throw err;
} );

await triggerUnhandledWarnings( );

index.setLogger( );

const linesWoColumns = splitLines( logger.mock.calls[ 0 ] )
.filter( line => line.includes( "logger.spec.js" ) )
.map( line => cutColumn( line ) );

const errorAndShared = splitLines( logger.mock.calls[ 0 ] )
.filter( line => line );

expect( linesWoColumns.length ).toBeGreaterThanOrEqual( 2 );
expect( linesWoColumns[ 0 ] ).not.toBe( linesWoColumns[ 1 ] );

expect( errorAndShared )
.toContain( " ==== Error at: ====================" );
expect( errorAndShared )
.toContain( " ==== Shared trace: ================" );
} );
} );
51 changes: 10 additions & 41 deletions test/register.spec.js
Original file line number Diff line number Diff line change
@@ -1,45 +1,14 @@

const { Finally, Try, delay } = require( 'already' );
require( '../register' );

const withConsoleSpy = fn => async ( ) =>
{
const oldError = console.error;
console.error = jest.fn( );
return Try( fn )
.then( ...Finally( ( ) =>
{
console.error = oldError;
} ) );
}
const {
withConsoleSpy,
triggerUnhandledWarnings,
splitLines,
cutColumn,
cutLocation,
} = require( './helpers' );

async function triggerUnhandledWarnings( )
{
await delay( 0 );
global.gc && global.gc( );
await delay( 0 );
}

function splitLines( lines )
{
return [ ].concat( ...lines.map( line => line.split( "\n" ) ) );
}

function cutColumn( line )
{
const m = line.match( /(.*:\d+):\d+\)?$/ );
if ( !m )
return line;
return m[ 1 ];
}
require( '../register' );

function cutLocation( line )
{
const m = line.match( /(.*):\d+:\d+\)?$/ );
if ( !m )
return line;
return m[ 1 ];
}

describe( "register", ( ) =>
{
Expand Down Expand Up @@ -151,7 +120,7 @@ describe( "register", ( ) =>
const errorAndShared = splitLines( console.error.mock.calls[ 0 ] )
.filter( line => line );

expect( linesWoColumns.length ).toBeGreaterThanOrEqual( 2 );
expect( linesWoColumns.length ).toBeGreaterThanOrEqual( 1 );
expect( linesWoColumns[ 0 ] ).not.toBe( linesWoColumns[ 1 ] );

expect( errorAndShared[ errorAndShared.length - 2 ] ).toBe(
Expand Down Expand Up @@ -180,7 +149,7 @@ describe( "register", ( ) =>
const errorAndShared = splitLines( console.error.mock.calls[ 0 ] )
.filter( line => line );

expect( linesWoColumns.length ).toBeGreaterThanOrEqual( 2 );
expect( linesWoColumns.length ).toBeGreaterThanOrEqual( 1 );
expect( linesWoColumns[ 0 ] ).not.toBe( linesWoColumns[ 1 ] );

expect( errorAndShared[ errorAndShared.length - 2 ] ).toBe(
Expand Down
3 changes: 2 additions & 1 deletion web/register-web.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@

import { logger, TraceablePromise } from "../lib/core";
import { logger, TraceablePromise, setLogger} from "../lib/core";

window.onunhandledrejection = function( event: PromiseRejectionEvent )
{
logger( event.reason, event.promise );
};

( < any >window ).Promise = TraceablePromise;
( < any >window ).setTraceUnhandledLogger = setLogger;

0 comments on commit 0d1df76

Please sign in to comment.