Giter VIP home page Giter VIP logo

vue-log's Introduction

vue-log

This npm package provides a system of log enhancements for vue applications.

Build Status NPM version NPM downloads MIT License

Purpose

vue-log enables you to implement multiple log levels with enhanced and coloured messages based on your environment. For example, you can log coloured debug messages to the console, discerning between sibling vue components in a list. In production you can send the same messages to your error reporting framework (for example Sentry/Raven) as breadcrumbs in case of an error occuring.

Quickstart

  1. Install the module

    npm install -S @dreipol/vue-log
  2. Register the plugin to your Vue instance

    import VueLog from '@dreipol/vue-log';
    Vue.use(VueLog);
  3. Start logging!

    // As a global instance
    const Log = Vue.log();
    
    function isPrimary(color) {
        if (!color) {
            Log.error(`Uh oh, no color was provided. That doesn't look right...`);
        }
    
        return ['red', 'green', 'blue'].indexOf(color) > -1;
    }
    
    // In a component: my-favourite-color
    export default {
        props: {
            color: String
        },
        mounted() {
            this.$log.debug('Component mounted!');
    
            if (isPrimary(this.color)) {
                this.$log.info('Favourite color is a primary color');
            } else {
                this.$log.warn(`Favourite color is no primary color, but that's ok... We don't judge!`);
            }
        }
    }

Config

You have multiple options to add a config either globally or when creating a new Logger.

Global config

When installing the plugin you may add a second parameter to extend the original presets. The new config will be used in two different ways:

  • As a preset whenever you create a new log instance explicitly (by using Vue.log)
  • As the config when creating a log instance implicitly (by using this.$log in a vue component)
    Vue.use(VueLog, { /* vue-log config */ });

Local config

For every log instance that you create explicitly (by using Vue.log), you can add a config object that will extend the global config.

    const Log = Vue.log({ /* vue-log config */ });

Config object

For a detailed description of the config object, please see the abstract-log documentation.

Environments

Switching between development and production code can be done like in many similar situations:

    Vue.use(VueLog, process.env.NODE_ENV === 'production' ? productionConfig : developmentConfig);

Examples

Logging to the console

Console output should work out of the box with the default preset.

Custom log messages

You can greatly customize your log messages by extending the log config object:

    Vue.use(VueLog, {
        logger: window.console,
        levels: [
            {
                name: 'log',
                fn: window.console.log,
                isCriticalError: false
            },
            {
                name: 'error',
                fn: window.console.error,
                isCriticalError: true
            },
        ],
        middlewares: [
            (result, { level, config }) => {
                const { isCriticalError } = level;

                if (isCriticalError) {
                    result.unshift('WARNING!!!');
                }

                return result;
            }
        ],
    });

Filter log levels

To filter below a certain threshold, you can use the filter property:

    const LOG_THRESHOLD = 'info';

    Vue.use(VueLog, {
        filter({ config, level }) {
            const logIndex = config.levels.findIndex(l => l.name === level.name);
            const thresholdIndex = config.levels.findIndex(l => l.name === LOG_THRESHOLD);

            return logIndex >= thresholdIndex;
        }
    });

Sentry

Sentry is a real-time crash reporting service. Its frontend reporting library is called Raven. When a javascript error occurs, Raven will report it to Sentry. You can add valuable debug information by storing what happened before the error occured:

    const { captureBreadcrumb } = window.Raven || {};
    const RAVEN_LEVEL_MAPPING = { debug: 'debug', info: 'info', warn: 'warning', error: 'error' };
    
    Vue.use(VueLog, {
        logger: window.Raven,
        proxy: false,
        levels: [
            { name: 'debug', fn: captureBreadcrumb },
            { name: 'info', fn: captureBreadcrumb },
            { name: 'warn', fn: captureBreadcrumb },
            { name: 'error', fn: captureBreadcrumb },
        ],
        middlewares: [
            (result, { level, config, statements }) => {
                result.push([
                    {
                        message: statements.toString ? statements.toString() : '',
                        category: 'vue-log',
                        level: RAVEN_LEVEL_MAPPING[level.name],
                        data: JSON.parse(JSON.stringify(config.context))
                    },
                ]);

                return result;
            }
        ]
    });

vue-log's People

Stargazers

 avatar Daniel Wilson avatar Timot Tarjani avatar Myles McNamara avatar Hamed Fathi avatar Haixing Hu avatar Gianluca Guarini avatar

Watchers

Philipp Läubli avatar James Cloos avatar Gianluca Guarini avatar Marco Glauser avatar Sidney Widmer avatar fabs avatar Gregor Falk avatar Simon Müller avatar  avatar Julia Strasser avatar  avatar  avatar

vue-log's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.