React Native Log

Learn via video courses
Topics Covered

Overview

In this article, we will explore React Native Logs, a simple and powerful logging library for React Native that allows you to customize your logging levels, transports, formats, and more. We will learn how to install, configure, and use React Native Logs in your React Native projects. We will also see some of the included preset transports and methods that React Native Logs provides.

Introduction

React Native Logs is a logging library for React Native that aims to be simple, powerful, and customizable. It is inspired by the popular Winston library for Node.js, but adapted for the React Native environment. React Native Logs allows you to:

  • Define your own logging levels with colors and severities
  • Choose from different transports to send your logs to different destinations (console, file, remote server, etc.)
  • Format your logs with timestamps, prefixes, colors, etc.
  • Filter your logs by severity, transport, or custom function
  • Use multiple arguments and interpolation in your log messages
  • Use preset transports for common scenarios (console, file, etc.)

React Native Logs is compatible with both iOS and Android platforms, and supports TypeScript definitions. It is also lightweight and easy to use, with a minimal API and sensible defaults.

Installation

To install React Native Logs in your React Native project, you can use npm or yarn:

You also need to install the peer dependencies of React Native Logs, which are react-native-fs (for file transport) and react-native-console-time-polyfill (for console.time support):

Quick Start

To start using React Native Logs in your project, you need to import the library and create a logger instance:

The default configuration of React Native Logs exposes four logging levels: debug, info, warn, and error. Each level has a corresponding method on the logger instance that you can use to log messages:

By default, all log messages are sent to the console transport, which prints them to the standard output (console.log, console.warn, console.error). You can see them in your terminal or in the developer menu of your app.

The default format of the log messages includes a timestamp, a level name, and a message:

You can also use multiple arguments and interpolation in your log messages:

The output will look like this:

Configuration

The default configuration of React Native Logs is suitable for most cases, but you can also customize it to fit your needs. You can pass a configuration object as the first argument of the createLogger function, which accepts the following properties:

  • levels: an object that defines the logging levels, their colors, and their severities. The keys are the level names, and the values are objects with color and severity properties. The color can be a string (e.g. “red”) or a number (e.g. 31) that represents an ANSI color code. The severity can be a number (e.g. 0) or a string (e.g. “none”) that represents the importance of the level. The lower the severity, the higher the importance. You can use any names and values for your levels, as long as they are consistent and unique.

  • transport: a function that defines how to send the log messages to a destination. The function receives a log object as an argument, which contains the level, message, and other properties of the log. The function can perform any action with the log object, such as printing it to the console, writing it to a file, sending it to a remote server, etc. You can use one of the included preset transports (see below), or create your own custom transport.

  • transportOptions: an object that defines some options for the transport function, such as level, filter, format, etc. The options vary depending on the transport function, but some common ones are:

  • level: a string or a number that defines the minimum severity of the logs to be sent to the transport. For example, if you set level to “warn”, only logs with severity equal or lower than “warn” will be sent to the transport. You can also use “none” to disable the transport completely.

  • filter: a function that defines a custom filter for the logs to be sent to the transport. The function receives a log object as an argument, and returns true or false depending on whether the log should be sent or not. For example, you can use filter to exclude some logs based on their content, source, etc.

  • format: a function that defines how to format the log messages before sending them to the transport. The function receives a log object as an argument, and returns a string or an array of strings that represent the formatted log message. For example, you can use format to add timestamps, prefixes, colors, etc. to your log messages.

Example with default configuration exposed:

Here is an example of how to create a logger instance with the default configuration exposed:

Custom levels

You can define your own logging levels with any names and values you want. For example, you can create a logger instance with five levels: trace, debug, info, warn, and error:

You can then use the corresponding methods on the logger instance to log messages with different levels:

The output will look like this:

Custom transport

You can also define your own custom transport function to send your logs to any destination you want. For example, you can create a custom transport that writes your logs to a file using the react-native-fs library:

You can then use the logger instance as usual to log messages:

Transport Options

As we have seen, you can use the transportOptions object to customize some options for your transport function. The options vary depending on the transport function, but some common ones are:

  • level: a string or a number that defines the minimum severity of the logs to be sent to the transport. For example, if you set level to “warn”, only logs with severity equal or lower than “warn” will be sent to the transport. You can also use “none” to disable the transport completely.
  • filter: a function that defines a custom filter for the logs to be sent to the transport. The function receives a log object as an argument, and returns true or false depending on whether the log should be sent or not. For example, you can use filter to exclude some logs based on their content, source, etc.
  • format: a function that defines how to format the log messages before sending them to the transport. The function receives a log object as an argument, and returns a string or an array of strings that represent the formatted log message. For example, you can use format to add timestamps, prefixes, colors, etc. to your log messages.

Here is an example of how to use the transportOptions object with the console transport:

You can then use the logger instance as usual to log messages:

The output will look like this:

Multiple Arguments

You can use multiple arguments and interpolation in your log messages, just like you would with console.log or other logging libraries. For example, you can log an array, an object, a number, or a string with placeholders:

The output will look like this:

Preset transports

React Native Logs provides some preset transports that you can use out of the box for common scenarios. You can import them from the react-native-logs package and pass them as the transport function of your logger instance. The preset transports are:

  • consoleSync: a synchronous transport that prints your logs to the standard output (console.log, console.warn, console.error). This is the default transport of React Native Logs.
  • colorConsoleSync: a synchronous transport that prints your logs to the standard output with colors (console.log, console.warn, console.error). The colors are based on the level colors defined in your configuration.
  • colorConsoleAsync: an asynchronous transport that prints your logs to the standard output with colors (console.log, console.warn, console.error). The colors are based on the level colors defined in your configuration. This transport uses setTimeout to defer the printing of the logs, which can improve performance but also introduce some delay and inconsistency in the order of the logs.
  • ansiColorConsoleSync: a synchronous transport that prints your logs to the standard output with ANSI colors (console.log, console.warn, console.error). The colors are based on the level colors defined in your configuration. This transport uses ANSI escape codes to add colors to your logs, which can make them more visible and readable in some terminals or editors. However, not all terminals or editors support ANSI colors, so you may see some unwanted characters in your output.
  • colorConsoleAfterInteractions: an asynchronous transport that prints your logs to the standard output with colors (console.log, console.warn, console.error) after all interactions have completed. The colors are based on the level colors defined in your configuration. This transport uses InteractionManager.runAfterInteractions to defer the printing of the logs until all interactions have finished. This can improve performance and responsiveness of your app, but also introduce some delay and inconsistency in the order of the logs.
  • rnFsFileAsync: an asynchronous transport that writes your logs to a file using the react-native-fs library. You need to install react-native-fs as a peer dependency to use this transport. You also need to provide a filePath option in the transportOptions object to specify where to write the logs.

Here is an example of how to use some of the preset transports:

You can then use the logger instance as usual to log messages:

The output will look like this:

The file will contain this:

Methods

React Native Logs provides some methods that you can use to interact with your logger instance. The methods are:

  • setSeverity: a function that sets the global severity level for your logger instance. This function accepts a level name as an argument and sets the severity level to the corresponding severity number defined in your configuration. For example, if you call logger.setSeverity(“info”), it will set the severity level to 2. This means that only logs with severity equal or lower than 2 will be sent to the transports. You can use this method to dynamically change the severity level of your logger instance at runtime.
  • getSeverity: a function that returns the current global severity level for your logger instance. This function returns a number that represents the severity level. For example, if you call logger.getSeverity(), it may return 2 if the severity level is set to “info”. You can use this method to check the current severity level of your logger instance.

Here is an example of how to use these methods:

Usage Tips

Here are some usage tips that can help you improve your logging experience with React Native Logs:

  • Logs only in development mode: If you want to log messages only in development mode and disable logging in production mode, you can use the DEV global variable that React Native provides. You can set the enabled option of your logger instance to DEV, which will be true in development mode and false in production mode. For example:
  • Global logger in React Native: If you want to use the same logger instance across your React Native app, you can create a global logger in a separate file and export it as a module. Then, you can import and use it in any component or file that needs logging. For example, you can create a file called logger.js with the following content:

Then, you can import and use it in any component or file that needs logging. For example, in App.js, you can do:

  • Use multiple transports: If you want to send your logs to different destinations, you can use multiple transports in your logger instance. For example, you can use colorConsoleSync transport to print your logs to the console with colors, and rnFsFileAsync transport to write your logs to a file. You can also specify different levels and options for each transport. For example:

Conclusion

  • React Native Logs is a logging library for React Native that supports multiple transports, custom levels, colors, filters, formats, and more.
  • To use React Native Logs, we need to install react-native-logs and react-native-fs as dependencies, import the createLogger function from the react-native-logs package, and use it to create a logger instance with optional configuration.
  • We can customize some options for our logger instance by passing a config object to the createLogger function. The config object can have properties like levels, transport, transportOptions, dateFormat, printLevel, printDate, and enabled.
  • We can log messages with different levels, colors, and formats by using the level name as a method of the logger instance. For example, logger.info(“This is an info message”).
  • React Native Logs provides some preset transports that we can use for common scenarios. The preset transports are consoleSync, colorConsoleSync, colorConsoleAsync, ansiColorConsoleSync, colorConsoleAfterInteractions, and rnFsFileAsync.
  • React Native Logs also provides some methods that we can use to interact with our logger instance. The methods are setSeverity and getSeverity. We can use them to dynamically change and check the global severity level of our logger instance.
  • We can use some usage tips to improve our logging experience with React Native Logs. The usage tips are logging only in development mode, using a global logger in React Native, and using multiple transports.

If you want to learn more about React Native Logs, you can check out its GitHub repository and documentation. You can also find some examples and demos in the repository.

We hope you enjoyed this article and found it useful. Happy logging!