Redescubriendo el console.log 2/2

En el artículo anterior ya tratamos sobre los principales métodos del objeto console, Aquí veremos el método log y algunos pequeños consejos para aprovechar mejor su funcionalidad.

Agrupar variables

Cuando los valores de las variables no son muy grandes puedes agruparlos para tener una mejor visualización

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const a = { v: 1 };
const b = { v: 2 };
const c = { v: 3 };
console.log("--Bad idea---");
console.log("a", a);
console.log("b", b);
console.log("c", c);
console.log("--Good idea---");
console.log({ a, b, c });
const a = { v: 1 }; const b = { v: 2 }; const c = { v: 3 }; console.log("--Bad idea---"); console.log("a", a); console.log("b", b); console.log("c", c); console.log("--Good idea---"); console.log({ a, b, c });
const a = { v: 1 };
const b = { v: 2 };
const c = { v: 3 };

console.log("--Bad idea---");
console.log("a", a);
console.log("b", b);
console.log("c", c);

console.log("--Good idea---");
console.log({ a, b, c });

También puedes usarlo para mostrar una sola variable;

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const dayOfWeek = "Monday";
console.log("--Bad idea---");
console.log("dayOfWeek", dayOfWeek);
console.log("\n--Good idea---");
console.log({dayOfWeek});
const dayOfWeek = "Monday"; console.log("--Bad idea---"); console.log("dayOfWeek", dayOfWeek); console.log("\n--Good idea---"); console.log({dayOfWeek});
const dayOfWeek = "Monday";

console.log("--Bad idea---");
console.log("dayOfWeek", dayOfWeek); 

console.log("\n--Good idea---");
console.log({dayOfWeek}); 

Agregarle color

Podemos personalizar los colores de nuestros mensajes, no se si sea muy útil, pero es divertido.

Ejemplo 1

Tomando el código del ejemplo anterior

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const dayOfWeek = "Monday";
console.log("%c%s","color: red;font-weight: bold;","Bad idea!");
console.log("dayOfWeek", dayOfWeek);
console.log("%c%s","color: green;font-weight: bold;","\nGood idea!");
console.log({dayOfWeek});
const dayOfWeek = "Monday"; console.log("%c%s","color: red;font-weight: bold;","Bad idea!"); console.log("dayOfWeek", dayOfWeek); console.log("%c%s","color: green;font-weight: bold;","\nGood idea!"); console.log({dayOfWeek});
const dayOfWeek = "Monday";

console.log("%c%s","color: red;font-weight: bold;","Bad idea!");
console.log("dayOfWeek", dayOfWeek); 

console.log("%c%s","color: green;font-weight: bold;","\nGood idea!");
console.log({dayOfWeek}); 

Ejemplo 2

Personalizando los mensajes de succes, error, warning e info

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function customLog(message, color='black') {
let logType = 'log';
switch (color) {
case 'success':
color = 'Green';
break
case 'info':
color = 'Blue';
logType = 'info';
break;
case 'error':
color = 'Red';
logType = 'error';
break;
case 'warning':
color = 'Orange';
logType = 'warn';
break;
default:
color = color
}
console[logType](`%c${message}`, `color:${color}`);
}
customLog('Success!', 'success')
customLog('Error!', 'error')
customLog('Warning!', 'warning')
customLog('Info...', 'info')
function customLog(message, color='black') { let logType = 'log'; switch (color) { case 'success': color = 'Green'; break case 'info': color = 'Blue'; logType = 'info'; break; case 'error': color = 'Red'; logType = 'error'; break; case 'warning': color = 'Orange'; logType = 'warn'; break; default: color = color } console[logType](`%c${message}`, `color:${color}`); } customLog('Success!', 'success') customLog('Error!', 'error') customLog('Warning!', 'warning') customLog('Info...', 'info')
function customLog(message, color='black') {
     let logType = 'log';
     switch (color) {
         case 'success':  
              color = 'Green';
              break
         case 'info':     
              color = 'Blue';
              logType = 'info';
              break;
         case 'error':   
              color = 'Red'; 
              logType = 'error';
              break;
         case 'warning':  
              color = 'Orange';
              logType = 'warn';
              break;
         default: 
              color = color
     }

     console[logType](`%c${message}`, `color:${color}`);
}


customLog('Success!', 'success')
customLog('Error!', 'error')
customLog('Warning!', 'warning')
customLog('Info...', 'info')

Ejemplo 3

Escribir mensaje con múltiples colores

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const customLog = (message, color = "black") => {
const colors = {
green: "green",
blue: "blue",
red: "red",
orange: "orange",
black: "black",
lime: "lime"
};
console.log(`%c${message}`, `color:${colors[color]}`);
};
customLog("Hello!!");
customLog("Hi green", "green");
customLog("Hi blue", "blue");
customLog("Hi red", "red");
customLog("Hi orange", "orange");
customLog("Hi lime", "lime");
const customLog = (message, color = "black") => { const colors = { green: "green", blue: "blue", red: "red", orange: "orange", black: "black", lime: "lime" }; console.log(`%c${message}`, `color:${colors[color]}`); }; customLog("Hello!!"); customLog("Hi green", "green"); customLog("Hi blue", "blue"); customLog("Hi red", "red"); customLog("Hi orange", "orange"); customLog("Hi lime", "lime");
const customLog = (message, color = "black") => {
    const colors = {
        green: "green",
        blue: "blue",
        red: "red",
        orange: "orange",
        black: "black",
        lime: "lime"
    };

    console.log(`%c${message}`, `color:${colors[color]}`);
};

customLog("Hello!!");
customLog("Hi green", "green");
customLog("Hi blue", "blue");
customLog("Hi red", "red");
customLog("Hi orange", "orange");
customLog("Hi lime", "lime");

Ejemplo 4

Si estas muy aburrido y quieres mostrar tus habilidades de hacker y mandar mensajes en el console.log puedes usar este truco, pero ten en consideración que solo funciona en google chrome.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
console.log("%cJavaScript is amazing!",
`\
font-size: 3em; \
background: red url("https://i.imgur.com/Uyw52SY.gif") \
no-repeat center center;\
background-size: 110% 110%; \
font-weight: bold; \
color: white; \
text-shadow: 0 0 1em black, 0 0 1em black, 0 0 1em black, 0 0 1em black, 0 0 1em black; \
padding: 1% 2% 25%; \
`)
console.log("%cJavaScript is amazing!", `\ font-size: 3em; \ background: red url("https://i.imgur.com/Uyw52SY.gif") \ no-repeat center center;\ background-size: 110% 110%; \ font-weight: bold; \ color: white; \ text-shadow: 0 0 1em black, 0 0 1em black, 0 0 1em black, 0 0 1em black, 0 0 1em black; \ padding: 1% 2% 25%; \ `)
console.log("%cJavaScript is amazing!",
    `\
    font-size: 3em; \
    background: red url("https://i.imgur.com/Uyw52SY.gif") \
    no-repeat center center;\
    background-size: 110% 110%; \
    font-weight: bold; \
    color: white; \
    text-shadow: 0 0 1em black, 0 0 1em black, 0 0 1em black, 0 0 1em black, 0 0 1em black; \
    padding: 1% 2% 25%; \
`)

No usar en producción

Evite usar el objeto console en producción, a parte de que puedes exponer información no deseada puede ralentizar tu aplicación.

¿Conoces algun truco o tip sobre el console.log? colócalo en los comentarios

benjamin
Me llamo Benjamín Gonzales B, soy desarrollador de software con más de 15 años de experiencia, socio funduador de la empresa GNBIT. Me apasiona todo lo relacionado a las nuevas tecnologías, me gusta investigar , leer y aprender cada día algo nuevo. Desarrollo en PHP7+, JAVA, C#, JavaScript, entre otros y actualmente  estoy experimentando con lenguajes funcionales como: Erlang, Clojure y Scala 

1 Comment

Leave a Comment

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

This site uses Akismet to reduce spam. Learn how your comment data is processed.