Files
react-native/Libraries/Core/Devtools/logToConsole.js
T
Christoph Nakazawa db9fc38893 Log console.log invocations to the Metro terminal.
Summary:
People ask "How do you use `console.log` with React Native?" and there is no good answer. This diff aims to stop people from asking this question.

See https://fb.workplace.com/groups/rn.core/permalink/2372327062999018/ for context.

This logging relies on network requests which can cause logs to show up out-of-order. To reduce the likelihood I queue every log message on the server for a maximum of 200ms. There could be other methods, like using websocket, but that seems more complex than is necessary at least in the beginning.

I considered various throttling strategies because this could be quite chatty and possibly problematic, however I think we can just ship this and iterate based on feedback. On my very underpowered laptop I logged a random number every 10 milliseconds and it didn't cause any issues or slowdown.

Reviewed By: gaearon

Differential Revision: D15559151

fbshipit-source-id: 552001622af0937ae3a37d2bd8c1b96e7ca52020
2019-05-31 00:45:03 -07:00

34 lines
680 B
JavaScript

/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
'use strict';
const getDevServer = require('./getDevServer');
let ID = 0;
function logToConsole(
level: 'trace' | 'info' | 'warn' | 'log',
data: Array<mixed>,
) {
let body;
try {
body = JSON.stringify({id: ID++, level, data});
} catch (error) {
body = JSON.stringify({id: ID++, level, data: [error.message]});
}
fetch(getDevServer().url + 'log-to-console', {
method: 'POST',
body,
});
}
module.exports = logToConsole;