Logging in vuejs without console.log

11,367

Solution 1

Consider building your own simple wrapper which will work everywhere, assuming you are using Webpack, like following:

declare const NODE_ENV: any;

export function log(message: String, level?: 'info' | 'warn' | 'error') {

    // WHEN RUNNING WEBPACK WITH `PRODUCTION` build,
    // IT WILL REMOVE FOLLWOING CODE.

    if (NODE_ENV !== 'production') {

        if (level === 'error') {
            console.error(message);
        } else if (level === 'warn') {
            console.warn(message);
        } else {
            console.log(message);
        }
    }
}

Being a simple function, you can literally import this anywhere in your code including component files or other non-component files. The important point here is to note the use of NODE_ENV variable which will be injected by Webpack when running in Production mode. Similar, setup exists for Rollup and other bundlers. Read more about this here. When Webpack is bundling the code with production mode, it will ignore the code inside if (NODE_ENV !== 'production') { /* some code */ } construct.

Also, if you need to wrap it inside a plugin so that it is available on every component instance using this pointer then:

const MyLogger = {
    install(Vue: Vue, options: any) {

        // Add an instance method
        Vue.prototype.log = log;
    }
};

Vue.install(MyLogger);

Of course, if you are using TypeScript, then you must teach TypeScript using module augmentation like this:

import Vue from 'vue';

declare module 'vue/types/vue' {
    interface Vue {
        log(message: string, level?: 'info' | 'warn' | 'error'): void;
    }
}

This above snippet should be present inside your typings folder like specified using tsconfig.json. The directory path would be: ROOT/typings/vue/index.d.ts.

In tsconfig.json file, typings array should be set to:

"typeRoots": [
    "./node_modules/@types",
    "./typings"
],

Solution 2

It is also possible to use the vuejs3-logger in modules that are not components. These are the required steps:

  1. create a module logger.js with content
import VueLogger from 'vuejs3-logger'
import { createApp } from 'vue'

const isProduction = process.env.NODE_ENV === 'production';

const vlOptions = {
    isEnabled: true,
    logLevel : isProduction ? 'info' : 'debug',
    stringifyArguments : false,
    showLogLevel : true,
    showMethodName : true,
    separator: '|',
    showConsoleColors: true
};

// create a dummy app that can be used as logger in other js modules
const app = createApp({})
app.use(VueLogger, vlOptions);
const logger = app.config.globalProperties.$log;

export {VueLogger, vlOptions, logger};
  1. use this to create your Vue app as usual
import {createApp} from 'vue'
import {VueLogger, vlOptions} from './logger.js'
import App from '../components/App.vue'

createApp(App)
  .use(VueLogger, vlOptions)
  .mount('#app');
  1. In your external JavaScript module, do this:
import {logger} from './logger.js'

logger.debug("Hi there!")

The point is that when you change the logging level in logger.js, all your JavaScript modules will adapt to this logging level as well.

Share:
11,367

Related videos on Youtube

jalal
Author by

jalal

Originally a C/C++ programmer, most of my work over the last decade has been in web programming, using PHP and Javascript (although I've done spells with Perl and Java). I have carried over an interest in the art of programming itself, particularly in program design, object orientation, abstraction and so on, all those interesting things that are inherent in C++/Java but entirely optional in PHP.

Updated on May 25, 2022

Comments

  • jalal
    jalal almost 2 years

    I want to have console logging while I'm developing in VueJS but want it disabled for production.

    There is a module vuejs-logger that works fine inside of a Vue component and will be disabled in production mode. But it will not work (for instance) in my service files or library files (outside of Vue instance), nor in Vuex.

    Does anyone have any other suggestions? Vuejs integrated or otherwise?

    Stay safe, TIA

    Edit: Just to clarify, vuejs-logger Typescript integration is the real problem. It throws up so many TS errors that I cannot use it. The actual JS logging seems to work... I'm still interested in other solutions that may work smoothly.

  • jalal
    jalal about 4 years
    Thanks for the very thorough answer. I'll give both ideas a try later today. Great!