Console API
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
console.context()
console.context(label)
Parameters
label- : A string used to name the context. Messages logged through the returned object are associated with this name. Defaults to
"anonymous".
- : A string used to name the context. Messages logged through the returned object are associated with this name. Defaults to
Return value
A new object that has most of the methods of the console object, such as console/log_static, console/warn_static, console/count_static, and console/time_static. 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 console/count_static and console/time_static labels used on one context don't affect the same labels on the global console object or on another context. Calling console/clear_static 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
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
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
- console/count_static
- console/time_static
- Proposal to specify
console.context()in the Console Standard
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
