Skip to content

Commit

Permalink
Log console invocations to the terminal. (react-native-community#426)
Browse files Browse the repository at this point in the history
  • Loading branch information
cpojer authored and dratwas committed Jul 12, 2019
1 parent 9980667 commit 3f15d01
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import getSecurityHeadersMiddleware from './getSecurityHeadersMiddleware';
import loadRawBodyMiddleware from './loadRawBodyMiddleware';
import openStackFrameInEditorMiddleware from './openStackFrameInEditorMiddleware';
import openURLMiddleware from './openURLMiddleware';
import logToConsoleMiddleware from './logToConsoleMiddleware';
import statusPageMiddleware from './statusPageMiddleware';
import systraceProfileMiddleware from './systraceProfileMiddleware';
import getDevToolsMiddleware from './getDevToolsMiddleware';
Expand Down Expand Up @@ -53,6 +54,7 @@ export default class MiddlewareManager {
.use('/debugger-ui', serveStatic(debuggerUIFolder))
.use(openStackFrameInEditorMiddleware(this.options))
.use(openURLMiddleware)
.use(logToConsoleMiddleware)
.use(copyToClipBoardMiddleware)
.use(statusPageMiddleware)
.use(systraceProfileMiddleware)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

import chalk from 'chalk';

let cache = [];
let timer;

const log = ({level, data, id}) => {
const logFunction = level !== 'trace' && console[level] ? level : 'log';
const color =
level === 'error' ? 'red' : level === 'warn' ? 'yellow' : 'white';

console[logFunction].apply(console, [
chalk.inverse[color].bold(` ${level.toUpperCase()} `),
...data,
]);
};

// Hold messages and flush them to reduce the amount of out-of-order logs
const flush = () => {
timer = null;
cache.sort((a, b) => a.id - b.id).forEach(log);
cache = [];
};

export default (req, res, next) => {
if (req.url === '/log-to-console') {
cache.push(JSON.parse(req.rawBody));
if (!timer) {
timer = setTimeout(flush, 200);
}

res.end('OK');
} else {
next();
}
};

0 comments on commit 3f15d01

Please sign in to comment.