Colors in JavaScript console

前端 未结 27 2125
说谎
说谎 2020-11-22 11:42

Can Chrome\'s built-in JavaScript console display colors?

I want errors in red, warnings in orange and console.log\'s in green. Is that possible?

相关标签:
27条回答
  • 2020-11-22 12:07

    Try this:

    var funcNames = ["log", "warn", "error"];
    var colors = ['color:green', 'color:orange', 'color:red'];
    
    for (var i = 0; i < funcNames.length; i++) {
        let funcName = funcNames[i];
        let color = colors[i];
        let oldFunc = console[funcName];
        console[funcName] = function () {
            var args = Array.prototype.slice.call(arguments);
            if (args.length) args = ['%c' + args[0]].concat(color, args.slice(1));
            oldFunc.apply(null, args);
        };
    }
    

    now they all are as you wanted:

    console.log("Log is green.");
    console.warn("Warn is orange.");
    console.error("Error is red.");
    

    note: formatting like console.log("The number = %d", 123); is not broken.

    0 讨论(0)
  • 2020-11-22 12:08

    I create now the log-css.js https://codepen.io/luis7lobo9b/pen/QWyobwY

    // log-css.js v1
    const log = console.log.bind();
    const css = function(item, color = '#fff', background = 'none', fontSize = '12px', fontWeight = 700, fontFamily) {
        return ['%c ' + item + ' ', 'color:' + color + ';background:' + background + ';font-size:' + fontSize + ';font-weight:' + fontWeight + (fontFamily ? ';font-family:' + fontFamily : '')];
    };
    // example
    log(...css('Lorem ipsum dolor sit amet, consectetur adipisicing elit.', 'rebeccapurple', '#000', '14px'));
    
    0 讨论(0)
  • 2020-11-22 12:09

    I wrote template-colors-web https://github.com/icodeforlove/Console.js to allow us to do this a bit easier

    console.log(c`red ${c`green ${'blue'.bold}.blue`}.green`.red);
    

    The above would be extremely hard to do with the default console.log.

    For a live interactive demo click here.

    0 讨论(0)
  • 2020-11-22 12:09

    Update:

    I have written a JavaScript library last year for myself. It contains other features e.g verbosity for debug logs and also provides a download logs method that exports a log file. Have a look at the JS Logger library and its documentation.


    I know It's a bit late to answer but as the OP asked to get custom color messages in console for different options. Everyone is passing the color style property in each console.log() statement which confuses the reader by creating complexity in the code and also harm the overall look & feel of the code.

    What I suggest is to write a function with few predetermined colors (e.g success, error, info, warning, default colors) which will be applied on the basis of the parameter passed to the function.

    It improves the readability and reduces the complexity in the code. It is too easy to maintain and further extend according to your needs.


    Given below is a JavaScript function that you have to write once and than use it again and again.

    function colorLog(message, color) {
    
        color = color || "black";
    
        switch (color) {
            case "success":  
                 color = "Green"; 
                 break;
            case "info":     
                    color = "DodgerBlue";  
                 break;
            case "error":   
                 color = "Red";     
                 break;
            case "warning":  
                 color = "Orange";   
                 break;
            default: 
                 color = color;
        }
    
        console.log("%c" + message, "color:" + color);
    }
    

    Output:


    The default color is black and you don't have to pass any keyword as parameter in that case. In other cases, you should pass success, error, warning, or info keywords for desired results.

    Here is working JSFiddle. See output in the browser's console.

    0 讨论(0)
  • 2020-11-22 12:09

    I created a package for the same. cslog

    Install it with

    npm i cslog
    

    Use It like this

    import log from 'cslog'
    
    log.h2("This is heading 2")
    log.p("This is colored paragraph")
    log.d(person, "Person Info")
    

    You can give your custom colors as well. here

    0 讨论(0)
  • 2020-11-22 12:10

    You can use a custom stylesheet to color your debugger. You can put this code in C:\Documents and Settings\<User Name>\Local Settings\Application Data\Google\Chrome\User Data\Default\User StyleSheets\Custom.css if you are in WinXP, but the directory varies by OS.

    .console-error-level .console-message-text{
        color: red;
    }
    
    .console-warning-level .console-message-text {
        color: orange;
    }
    
    .console-log-level .console-message-text {
        color:green;
    }
    
    0 讨论(0)
提交回复
热议问题