Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debug logging with React

I'd like to:

  1. insert debug logging statements into my code that I want to be able to turn on and off during development; and
  2. then have these statements stripped out entirely in production.

To accomplish stripping out the logs for production, I've seen that the React project itself uses this idiom:

if ("production" !== process.env.NODE_ENV) {
    // warn or log or whatever
}

By compiling the modules with process.env.NODE_ENV set to "production" and then running the bundle through a dead code eliminator like UglifyJS, the logs will be eliminated as unreachable.

This is fine, but are there more flexible solutions? I'm thinking something like the debug() Node module, or really some even more powerful, like the Java logging APIs.

I am wondering why I'm not finding a module that combines the ("production" !== process.env.NODE_ENV) approach with debug().

like image 1000
Dmitry Minkovsky Avatar asked Oct 02 '15 03:10

Dmitry Minkovsky


People also ask

How do I debug in Reactjs?

There are two main ways in which we can use them: By writing the debugger statement in our source code. By clicking on a specific line of the code in the Chrome web browser (or Firefox, Edge, etc.) Developer Tools.

Can you console log in React?

log() in React JS. Console. log() is one of the most useful functions you'll ever use. It allows you to debug, create proof of concepts, and even add functionality to a web app.

How do you add logs in react JS?

Quick Start. import { logger } from "react-native-logs"; var log = logger. createLogger(); log. debug("This is a Debug log"); log.info("This is an Info log"); log.


1 Answers

var debug = function(msg) {
    if ("production" !== process.env.NODE_ENV) console.log(msg);
}
module.exports = debug;

Usage:

var debug = require("debug");
debug("some logs");

Sorry, I couldn't help myself ;). But really, there are plenty of JS logging frameworks out there (although I honestly think the solution above is simple enough that you don't need to over-complicate things).

like image 193
Kabir Sarin Avatar answered Sep 18 '22 08:09

Kabir Sarin