console (Built-in)

Built-in logging functionality in JavaScript/Node.js. Provides basic methods like console.log, console.error, console.warn. Immediately available without configuration and widely used for development and debugging. Limited functionality for production environments.

Logging LibraryJavaScriptNode.jsBrowserDebugStandard

Library

console (Built-in)

Overview

console is the built-in logging functionality in JavaScript/Node.js, serving as the most fundamental and essential tool for development and debugging purposes. It provides basic methods like console.log, console.error, console.warn, and is immediately available without any configuration. Working across both browser and Node.js environments, it's optimized for quick debugging and information output during development stages. While its functionality is limited in production environments, it's recommended to use alongside dedicated logging libraries for full-scale applications.

Details

The console API is implemented as a built-in feature of the V8 engine, making it the most familiar logging method for JavaScript developers. Even in 2025, its use in development and prototyping stages remains unchanged, still being the first choice for simple scripts and quick debugging. Browser integration with developer tools supports format specifiers (%s, %d, %o, etc.) and CSS styling (%c). In Node.js environments, integration with diagnostics channels enables performance monitoring and debug information collection. It provides diverse functionality including multiple log levels (log, debug, info, warn, error), timing features (time/timeEnd), grouping (group/groupEnd), and profiling (profile/profileEnd).

Key Features

  • Immediate availability without configuration: Ready to use without imports or setup
  • Diverse logging methods: Rich methods including log, debug, info, warn, error, trace
  • Formatting capabilities: printf-style format specifiers and CSS styling support
  • Performance measurement: Execution time measurement with time/timeEnd
  • Structured display: Organized output with table, dir, and group
  • Cross-platform support: Consistent behavior across browser and Node.js

Advantages and Disadvantages

Advantages

  • Overwhelming adoption rate in JavaScript ecosystem with low learning cost
  • Immediate availability without configuration for improved development efficiency
  • Excellent integration with browser developer tools and debugging experience
  • Performance monitoring through diagnostics channel integration in Node.js environment
  • Flexible output control with format specifiers and CSS styling
  • Lightweight with minimal impact on other libraries

Disadvantages

  • Limited functionality in production environments and difficulty in log management
  • Lack of log level control and filtering capabilities
  • Absence of file output and external service integration features
  • Performance impact when outputting large amounts of logs
  • Limitations in structured logging and analytics tool integration
  • Insufficient functionality for full-scale applications

Reference Pages

Code Examples

Basic Log Output

// Basic log output
console.log('Hello, World!');
console.log('User info:', user);
console.log('Calculation result:', result);

// Output multiple values simultaneously
console.log('Name:', name, 'Age:', age, 'City:', city);

// Combination with template literals
console.log(`User ${name} is ${age} years old`);

// Output objects and arrays
const user = { name: 'John Doe', age: 30, role: 'developer' };
const numbers = [1, 2, 3, 4, 5];

console.log('User object:', user);
console.log('Number array:', numbers);

// JSON format output
console.log('JSON format:', JSON.stringify(user, null, 2));

Log Level Output

// Using various log levels
console.debug('Debug info: Checking variable values');
console.info('Info: Application started successfully');
console.warn('Warning: Deprecated API is being used');
console.error('Error: Database connection failed');

// Error objects and stack traces
try {
  throw new Error('Sample error');
} catch (error) {
  console.error('Exception occurred:', error);
  console.trace('Stack trace:');
}

// Conditional checks with assert
const value = 10;
console.assert(value > 5, 'value must be greater than 5');
console.assert(value < 5, 'This condition is false, so message will be displayed');

// Counter functionality
console.count('Function call');
console.count('Function call');
console.count('Error occurred');
console.countReset('Function call');

Format Specifiers and Styling

// printf-style format specifiers
const name = 'John Doe';
const age = 30;
const score = 85.6789;

console.log('String: %s', name);
console.log('Integer: %d', age);
console.log('Float: %f', score);
console.log('Decimal control: %.2f', score);
console.log('Object: %o', { name, age });

// CSS styling decoration (browser environment)
console.log('%cImportant Message', 'color: red; font-weight: bold; font-size: 16px;');
console.log('%cSuccess%c Operation completed', 
  'color: green; font-weight: bold;', 
  'color: black; font-weight: normal;'
);

// Combining multiple styles
console.log(
  '%cAPP%c %cSTARTED%c Application has launched',
  'background: blue; color: white; padding: 2px 5px; border-radius: 3px;',
  '',
  'background: green; color: white; padding: 2px 5px; border-radius: 3px;',
  ''
);

// Bullet point style
console.log('%c• Step 1: Initialization complete', 'color: #666;');
console.log('%c• Step 2: Data loading complete', 'color: #666;');
console.log('%c• Step 3: Processing started', 'color: #666;');

Structured Display and Grouping

// Table format display
const users = [
  { id: 1, name: 'John Doe', age: 30, department: 'Development' },
  { id: 2, name: 'Jane Smith', age: 28, department: 'Design' },
  { id: 3, name: 'Bob Johnson', age: 35, department: 'Sales' }
];

console.table(users);
console.table(users, ['name', 'age']); // Display specific columns only

// Detailed object display
const complexObject = {
  user: { name: 'John Doe', settings: { theme: 'dark', lang: 'en' } },
  metadata: { created: new Date(), version: '1.0.0' }
};

console.dir(complexObject, { depth: null }); // Display all levels
console.dir(complexObject, { colors: true }); // Color display (Node.js)

// Hierarchical display with grouping
console.group('User Processing');
console.log('Starting user info retrieval');
console.log('Connecting to database...');
console.group('Authentication Process');
console.log('Validating password...');
console.log('Generating token...');
console.groupEnd();
console.log('User info retrieval complete');
console.groupEnd();

// Collapsed group
console.groupCollapsed('Detailed Logs');
console.log('Detail info 1');
console.log('Detail info 2');
console.log('Detail info 3');
console.groupEnd();

Performance Measurement and Profiling

// Execution time measurement
console.time('Data processing time');

// Simulate time-consuming process
for (let i = 0; i < 1000000; i++) {
  Math.random();
}

console.timeEnd('Data processing time'); // "Data processing time: 45.123ms"

// Recording intermediate time
console.time('Overall processing');
console.log('Processing started');

setTimeout(() => {
  console.timeLog('Overall processing', 'Midpoint'); // Display intermediate time
}, 1000);

setTimeout(() => {
  console.timeEnd('Overall processing'); // Display total time
}, 2000);

// Running multiple timers simultaneously
console.time('API call 1');
console.time('API call 2');

// API call simulation
setTimeout(() => console.timeEnd('API call 1'), 500);
setTimeout(() => console.timeEnd('API call 2'), 800);

// CPU profiling (browser environment)
console.profile('Important process');
// Process to measure
for (let i = 0; i < 100000; i++) {
  document.createElement('div');
}
console.profileEnd('Important process');

Debugging and Troubleshooting

// Conditional log output
const DEBUG = true;
function debugLog(...args) {
  if (DEBUG) {
    console.log('[DEBUG]', ...args);
  }
}

debugLog('Debug info:', { status: 'ok', data: [1, 2, 3] });

// Function tracing
function functionA() {
  console.trace('functionA was called');
  functionB();
}

function functionB() {
  console.trace('functionB was called');
  functionC();
}

function functionC() {
  console.trace('functionC was called');
}

functionA(); // Display call stack

// Error handling and logging
async function fetchData(url) {
  try {
    console.log(`API call started: ${url}`);
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error(`HTTP Error: ${response.status}`);
    }
    
    const data = await response.json();
    console.log('API call successful:', data);
    return data;
    
  } catch (error) {
    console.error('API call error:', error);
    console.error('Error stack:', error.stack);
    throw error;
  }
}

// Variable state monitoring
function monitorVariable(obj, prop) {
  let value = obj[prop];
  Object.defineProperty(obj, prop, {
    get() {
      console.log(`${prop} was read:`, value);
      return value;
    },
    set(newValue) {
      console.log(`${prop} was changed:`, value, '->', newValue);
      value = newValue;
    }
  });
}

const state = { count: 0 };
monitorVariable(state, 'count');
state.count = 5; // Log will be output
console.log(state.count); // Log will be output

Extended Usage in Node.js Environment

// Creating custom console
const fs = require('fs');
const { Console } = require('console');

// Console for file output
const logFile = fs.createWriteStream('./app.log', { flags: 'a' });
const errorFile = fs.createWriteStream('./error.log', { flags: 'a' });

const fileConsole = new Console({
  stdout: logFile,
  stderr: errorFile
});

// Using standard and file consoles separately
console.log('Display to standard output');
fileConsole.log('Record to file:', new Date().toISOString());

// Integration with diagnostics channel (Node.js)
const diagnostics_channel = require('diagnostics_channel');

const channel = diagnostics_channel.channel('console');
channel.subscribe((message, name) => {
  console.log(`Console event: ${name}`, message);
});

// dir with format options
const complexData = {
  users: [
    { id: 1, name: 'John', nested: { a: 1, b: { c: 2 } } }
  ]
};

console.dir(complexData, {
  showHidden: false,
  depth: null,
  colors: true,
  maxArrayLength: 10,
  maxStringLength: 100,
  breakLength: 80,
  compact: false
});

// Logging on process exit
process.on('exit', () => {
  console.log('Application terminating');
});

process.on('uncaughtException', (error) => {
  console.error('Uncaught exception:', error);
  process.exit(1);
});