Different ways to maintain the original syntax highlighting colors in JavaScript console

Upon closer inspection near the green arrows, you can see that the default console.log function colorizes values based on their type, distinguishing between string and number.

https://i.sstatic.net/MtO8l.png

In contrast, highlighted near the red arrows is my attempt at using Winston to format logs in a specific manner; unfortunately, this approach abandoned the colorization of those values.

Check out the Replit demo here

function getArgumentsPreserved(providedArguments: Arguments): string {
  // https://nodejs.org/en/knowledge/getting-started/how-to-use-util-inspect/
  // https://github.com/chalk/chalk/issues/118#issuecomment-1221385194
  return util.inspect(providedArguments, { colors: false, depth: null });
}

const simpleConsoleLogging = winston.format.combine(
  // Simple console logging for local environment.
  winston.format.timestamp(),
  winston.format.printf((info) => {
    const { level, message, timestamp, ...rest } = info;
    const coloredTimestampAndLevel = colorizer.colorize(level, `${timestamp} ${level}:`);

    //const syntaxHighlightedObjects = Object.keys(rest).length > 0 ? getArgumentsPreserved(rest) : '';
    const syntaxHighlightedObjects = Object.keys(rest).length > 0 ? JSON.stringify(rest) : ''; // TODO: How can we reenable the syntax coloring that console.log had by default?
    return `${coloredTimestampAndLevel} ${message} ${syntaxHighlightedObjects}`; // https://github.com/winstonjs/winston/issues/1388#issuecomment-432932959
  }),
);

Despite trying with util.inspect, I have yet to achieve the desired outcome.

UPDATE

Take a look at the updated version here.

We are very close to solving the issue!

However, as seen in the screenshot, keys like 'abc' and 'def' seem to be missing.

https://i.sstatic.net/rAAnz.png

function getArgumentsPreserved(providedArguments: Arguments): string {
  if (Object.keys(providedArguments).length > 0) {
    const copiedArr = getRealKeys(providedArguments);
    // https://nodejs.org/en/knowledge/getting-started/how-to-use-util-inspect/
    // https://github.com/chalk/chalk/issues/118#issuecomment-1221385194
    return util.inspect(copiedArr, { colors: true, depth: null });
  } else {
    return '';
  }
}

function getRealKeys(rest: Arguments) {
  const result: string[] = [];
  Object.keys(rest).forEach(key => {
    result.push(rest[key])
  })
  return result;
}

const simpleConsoleLogging = winston.format.combine(
  // Simple console logging for local environment.
  winston.format.timestamp(),
  winston.format.printf((info) => {
    const { level, message, timestamp, ...rest } = info;
    const coloredTimestampAndLevel = colorizer.colorize(level, `${timestamp} ${level}:`);

    //const syntaxHighlightedObjects = Object.keys(rest).length > 0 ? util.inspect(copiedArr, undefined, undefined, true) : ''; // https://stackoverflow.com/questions/74186705/how-to-preserve-default-syntax-highlighting-colors-in-javascript-console
    const syntaxHighlightedObjects = getArgumentsPreserved(rest); // https://stackoverflow.com/questions/74186705/how-to-preserve-default-syntax-highlighting-colors-in-javascript-console

    return `${coloredTimestampAndLevel} ${message} ${syntaxHighlightedObjects}`; // https://github.com/winstonjs/winston/issues/1388#issuecomment-432932959
  }),
);

Answer №1

console.log in Node.js utilizes the inspect function from the internal util module, offering a convenient alternative:

const syntaxHighlightedObjects = util.inspect(rest, undefined, undefined, true);

The final parameter determines whether to include colors (which we definitely want). The second and third parameters control "show hidden properties" and "depth to display," respectively.


If the goal is to solely showcase the essential keys, this approach can be taken:

function getArgumentsPreserved(providedArguments: Arguments): string {
  if (Object.keys(providedArguments).length > 0) {
    const copied = Object.fromEntries(Object.entries(providedArguments));
    
    return util.inspect(copied, { colors: true, depth: null, showHidden: false });
  } else {
    return '';
  }
}

This method relies on Object.entries to extract only the object's own enumerable keys that were initially sought. Subsequently, Object.fromEntries efficiently reconstructs an object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve specific information from a group of data using Mongoose?

I need assistance with extracting the number from a collection that contains only a name and a number. I also want to either change the number or store it in a variable. How can I achieve this? let dataSchema = new mongoose.Schema({ name: String ...

Transforming data structures into arrays using Javascript

Could someone help me with converting the following code snippet? const words = {told: 64, mistake: 11, thought: 16, bad: 17} I need it to be transformed into: const words = [ {text: 'told', value: ...

Protractor unable to locate elements using by.repeater

What is the best method for targeting this repeater with Protractor? <a ng-repeat="item in filteredItems = (items | filter:'abc')">{{item}}</a> ...

Tips on properly declaring props in Typescript when a parent component is passing props down to its children componentsуж

When a parent component clones its children to pass props to them, how can we specify the type of props for the children? I'm encountering an issue because injectedProps is expected in the Child component const Parent: React.SFC<ParentProps> = ...

Having trouble toggling classes with mouseup in Wordpress Underscores theme

While I'm utilizing Underscores as the foundation theme for my website, one aspect that I particularly appreciate is its incorporation of a functional mobile navigation component. However, since my site is essentially single-page, the navigation remai ...

Ensure the proper utilization of properties

Consider a scenario where I have a structure that defines a user along with their login and given name: export interface User { login: string; name: string; } Now, my objective is to make an API call using the user's login information: const fo ...

`What can be done if ng-if is not responding?`

I'm facing an issue where I want to display a link <a href> only when a certain condition is met, but the link doesn't show up as expected. I have already attempted to experiment with changing the position of the code (inside or outside of ...

Retrieving data from a parent object within an iframe on a different origin

In order to incorporate a feature on various websites, I am looking to embed an iframe with JavaScript. This iframe should have the ability to interact with the parent object and display or hide certain elements on the webpage. The main HTML file includes ...

Managing field placement as the table height grows: tips and tricks

I am encountering an issue with my dynamic form. When I click on the add button, a new row is added to the table. However, once there are more than 6 rows added, the table height starts covering the fields. How can I go about setting this so that the field ...

What could be causing the sluggishness in my jQuery script that checks for required input fields?

My goal is to utilize jQuery to check for required input fields in browsers that do not recognize the required HTML tag. Below is the jQuery script I am using. $('div').on('submit', '#myform', function(e){ e.stopProp ...

Updating the Bootstrap entry dynamically within the @NgModule module

My web application has a specific requirement where it can only be accessed through example.com/index.html without any parameters. The backstory behind this restriction is quite lengthy, so let's not delve into that. Within the index.html file, I have ...

Is it necessary to exclude the 'scripts' folder from your Aurelia project's .gitignore file?

Should I exclude the 'scripts' directory that Aurelia is building to in my CLI project from Git by adding it to .gitignore, or is there a specific purpose for tracking changes to this directory? ...

Error message "TypeError: onClick is not a function" occurs when attempting to use a prop in a functional component

I am encountering issues while trying to utilize the onclick function as props. It shows an error message 'TypeError: onClick is not a function' when I click. What should I do? 7 | <Card 8 | onClick={() => onClick(dish ...

The array is not empty but the length is being displayed as zero

I am facing an issue in my project where I can successfully print the array in console, but I am unable to retrieve the length and access the first element. Here is the code snippet: checkout.component.ts: ngOnInit() { this.booksInCheckout = this.ch ...

Retrieve an item from a table in VUE upon clicking

I am currently using Vue Bootstrap and I want to be able to access the item when a row in the table is clicked. I have set up a table and a clickmeRow method to handle the action on the clicked item. <b-table-lite hover :items="it ...

Setting up Express routes in a separate file from the main one: a step-by-step

My goal is to organize my routes separately from the main app.js file using the following file structure. I attempted to create a api/user/ post API but encountered a 404 error. Any suggestions on how to resolve this issue with the given file structure? . ...

generate a collection using a string of variables

I'm looking for a way to pass a string as the name of an array to a function, and have that function create the array. For example: createArray('array_name', data); function createArray(array_name, data){ var new_array = []; // pe ...

Why would you need multiple root handlers?

One interesting feature to note is that multiple callback functions can be used as middleware to handle a request. These callbacks can take on different forms - they could be in the form of a single function, an array of functions, or even a combination of ...

Multiple keyup events being triggered repeatedly

Currently, I am developing an Angular 4 application. Within my component's HTML, there is a textbox where users can input text. As soon as the user starts typing, I want to trigger an API call to retrieve some data. The current issue I am facing is t ...

Working with nested arrays in Mongoose/Javascript: Adding an Object to an Array within another Array

I have been attempting to add an object to an array that is nested inside another Array in Mongoose. Essentially, it's like having comments for the comments. Below is the structure of my schema: const Schema = new mongoose.Schema ({ name: {type: Str ...