console: context() static method

Non-standard: This feature is not standardized. We do not recommend using non-standard features in production, as they have limited browser support, and may change or be removed. However, they can be a suitable alternative in specific cases where no standard option exists.

Note: This feature is available in Web Workers.

The console.context() static method creates a new console context: an object with most of the same methods as the console object, whose messages are associated with an optional label. This lets you group and filter the messages that come from different parts of your code.

Syntax

js
console.context()
console.context(label)

Parameters

label Optional

A string used to name the context. Messages logged through the returned object are associated with this name. Defaults to "anonymous".

Return value

A new object that has most of the methods of the console object, such as log(), warn(), count(), and time(). It doesn't have a context() method itself.

Description

Every call to console.context() returns a new, independent console context. Messages logged through a context carry its label, which developer tools can use to identify where a message came from. For example, in the Chrome DevTools, you can type context:myLogger in the filter box to show only the messages logged through a context labeled myLogger.

Each context keeps its own state for counters and timers. This means that count() and time() labels used on one context don't affect the same labels on the global console object or on another context. Calling clear() on a context still clears the whole console.

Just like the methods of console, methods of a console context don't use the value of this, so you can pass them around as unbound functions.

Examples

Creating a named logger

js
const logger = console.context("myLogger");
logger.log("Hello");
logger.info("World");

Both messages appear in the console like messages logged with console.log() and console.info(). In Chrome DevTools, typing context:myLogger in the console filter box shows only these two messages.

Counters are separate for each context

js
const a = console.context("A");
const b = console.context("B");

console.count("hits"); // hits: 1
a.count("hits"); // hits: 1
a.count("hits"); // hits: 2
b.count("hits"); // hits: 1
console.count("hits"); // hits: 2

Browser compatibility

See also