Keywords: React Native | Logging | Debugging | Console | DevTools
Abstract: This article provides an in-depth exploration of logging techniques in React Native, covering basic console.log usage, platform-specific log viewing methods, React Native DevTools integration, custom log level configuration, and third-party logging library implementation. With detailed code examples and platform-specific guidance, it helps developers establish a comprehensive React Native debugging and monitoring system.
Basic Console Logging
In React Native development, the most fundamental logging approach is similar to web development, where you can directly use JavaScript's standard console object methods. Developers can utilize console.log, console.warn, console.error, and other methods to output debugging information.
For example, logging variable values in a component:
const userData = { name: "John Doe", age: 25 };
console.log("User data:", userData);
console.warn("This is a warning message");
console.error("Error occurred", errorObject);Log Viewing Methods
In React Native development environments, log viewing methods vary by platform:
Terminal Viewing: When running the React Native development server, logs are directly output to the Metro bundler terminal. Starting from React Native 0.29, platform-specific logs can be viewed using dedicated commands:
npx react-native log-ios
npx react-native log-androidiOS Platform Debugging: In the iOS simulator, press ⌘+D and select the Remote JS Debugging option. This opens Chrome Developer Tools at http://localhost:8081/debugger-ui, where console.log outputs can be viewed in the JavaScript console.
Modern Development Experience: Recent versions of React Native have simplified the log viewing process. console.log directly prints to the terminal running the react-native command without requiring special configuration.
React Native DevTools Integration
React Native 0.76 introduced built-in React Native DevTools, providing more powerful debugging support. This tool supports all React Native applications running the Hermes engine, which is optimized for React Native and serves as the default engine for Expo.
In the Console tab, console outputs can be filtered by log level using the Default levels dropdown menu. Note that console.debug verbose logs are not displayed by default. Starting from React Native 0.77, JavaScript logs will be removed from Metro, making React Native DevTools the recommended approach for log viewing.
Log Levels and Methods
React Native supports the same console methods as web browsers, with each method corresponding to different severity levels:
- Verbose: Detailed message logging for debugging purposes
- Info: Information logging when code functions as expected, such as successful user payments
- Warning: Warning event logging for potential issues
- Error: Error information logging
Common console methods and their levels:
console.debug("Debug information"); // Verbose level
console.log("Regular log"); // Info level
console.info("Information log"); // Info level
console.warn("Warning message"); // Warning level
console.error("Error message"); // Error levelPerformance Timing: Use console.time and console.timeEnd methods to measure operation duration:
console.time("calculateDistance");
calculateDistance("51.50, -0.08", "48.86, 2.30");
console.timeEnd("calculateDistance");Structured Logging
For production applications, logging objects is more valuable than logging strings:
console.error({
user: "Jane Smith",
service: "payment",
message: "Payment failed",
timestamp: new Date().toISOString()
});Structured logging creates JSON-parseable log files that can be queried like databases using auditing tools. It's recommended to predefine a set of log properties to ensure organized and searchable logs for smoother error tracking and analysis.
LogBox Configuration
React Native's LogBox tool displays errors and warnings as on-screen notifications with red or yellow badges. The LogBox API can be used to configure log ignoring:
import { LogBox } from 'react-native';
// Ignore all logs
LogBox.ignoreAllLogs();
// Ignore specific logs
LogBox.ignoreLogs([
'Warning: componentWillReceiveProps has been renamed',
/GraphQL error: .*/, // Substring or regex matching
]);Advanced Logging Library Integration
For projects requiring more advanced features, third-party logging libraries can be considered:
react-native-logs: Feature-rich logging library supporting custom log levels, file saving, custom transports, and more:
import { logger } from "react-native-logs";
const log = logger.createLogger({
severity: "debug",
levels: {
error: 0,
warn: 1,
info: 2,
http: 3,
verbose: 4,
debug: 5,
silly: 6
},
transport: consoleTransport,
transportOptions: {
colors: {
info: "blue",
warn: "magenta",
error: "red"
}
}
});
log.debug('Sign in button pressed');
log.error("New error occurred", errorObject);File Logging: Use fileAsyncTransport to save logs to files:
import { fileAsyncTransport } from "react-native-logs";
import * as FileSystem from 'expo-file-system';
const log = logger.createLogger({
transport: [consoleTransport, fileAsyncTransport],
transportOptions: {
FS: FileSystem,
fileName: `my-app_log.txt`,
filepath: FileSystem.documentDirectory
}
});Native Log Access
For projects containing native code, accessing Android or iOS native logs may be necessary:
Android Native Logs: Use Android Studio and Logcat to view native logs. First generate native code:
npx expo prebuild -p android
open -a "/Applications/Android Studio.app" ./androidiOS Native Logs: Use Xcode debugging tools on macOS:
npx expo prebuild -p ios
xed iosSystem-Level Log Monitoring
When needing to view all device activities (including other applications and the operating system), system-level commands can be used:
npx react-native log-android
npx react-native log-iosThese commands provide complete device-level log views, aiding in diagnosing complex system interaction issues.
Error Monitoring and Sentry Integration
Sentry serves as a complement to logging, focusing on error and exception reporting. Install the Sentry React Native SDK:
npx @sentry/wizard@latest -i reactNativeCapture exceptions in code:
import * as Sentry from '@sentry/react-native';
Sentry.captureException(new Error('Test error'));react-native-logs with Sentry Integration:
import { logger, sentryTransport } from "react-native-logs";
const log = logger.createLogger({
severity: "debug",
transport: sentryTransport,
transportOptions: {
SENTRY: Sentry,
errorLevels: "error",
},
});
log.warn("Send to Sentry as breadcrumb");
log.error("Send to Sentry as error");Through proper logging strategies and tool integration, developers can establish comprehensive React Native application monitoring and debugging systems, significantly improving development efficiency and problem diagnosis capabilities.