RCTLog.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. * @flow
  9. */
  10. 'use strict';
  11. const invariant = require('invariant');
  12. const levelsMap = {
  13. log: 'log',
  14. info: 'info',
  15. warn: 'warn',
  16. error: 'error',
  17. fatal: 'error',
  18. };
  19. let warningHandler: ?(Array<any>) => void = null;
  20. const RCTLog = {
  21. // level one of log, info, warn, error, mustfix
  22. logIfNoNativeHook(level: string, ...args: Array<any>): void {
  23. // We already printed in the native console, so only log here if using a js debugger
  24. if (typeof global.nativeLoggingHook === 'undefined') {
  25. RCTLog.logToConsole(level, ...args);
  26. } else {
  27. // Report native warnings to LogBox
  28. if (warningHandler && level === 'warn') {
  29. warningHandler(...args);
  30. }
  31. }
  32. },
  33. // Log to console regardless of nativeLoggingHook
  34. logToConsole(level: string, ...args: Array<any>): void {
  35. const logFn = levelsMap[level];
  36. invariant(
  37. logFn,
  38. 'Level "' + level + '" not one of ' + Object.keys(levelsMap).toString(),
  39. );
  40. console[logFn](...args);
  41. },
  42. setWarningHandler(handler: typeof warningHandler): void {
  43. warningHandler = handler;
  44. },
  45. };
  46. module.exports = RCTLog;