Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Error Logging in JavaScript

Build error loggers in JavaScript: a simple JSON logger, structured logs with metadata, log levels and an aggregator that counts errors. Explanation and output.

IntermediateJavaScript Error HandlingExample 6 of 10
error-logging.js
1// Method 1: Simple error logger
2class ErrorLogger {
3 log(error, level = 'error') {
4 const logEntry = {
5 level: level,
6 message: error.message,
7 stack: error.stack,
8 timestamp: new Date().toISOString()
9 };
10
11 console[level](JSON.stringify(logEntry, null, 2));
12 }
13}
14
15const logger = new ErrorLogger();
16try {
17 throw new Error('Test error');
18} catch (error) {
19 logger.log(error);
20}
21
22// Method 2: Structured logging
23class StructuredLogger {
24 log(error, metadata = {}) {
25 const logEntry = {
26 error: {
27 name: error.name,
28 message: error.message,
29 stack: error.stack
30 },
31 metadata: metadata,
32 timestamp: new Date().toISOString(),
33 environment: 'production'
34 };
35
36 console.error(JSON.stringify(logEntry));
37 }
38}
39
40// Method 3: Error levels
41const LogLevel = {
42 DEBUG: 'debug',
43 INFO: 'info',
44 WARN: 'warn',
45 ERROR: 'error',
46 FATAL: 'fatal'
47};
48
49class LeveledLogger {
50 log(error, level = LogLevel.ERROR) {
51 const entry = {
52 level: level,
53 error: error.message,
54 timestamp: Date.now()
55 };
56
57 if (level === LogLevel.ERROR || level === LogLevel.FATAL) {
58 entry.stack = error.stack;
59 }
60
61 console.log(JSON.stringify(entry));
62 }
63}
64
65// Method 4: Error aggregation
66class ErrorAggregator {
67 constructor() {
68 this.errors = new Map();
69 }
70
71 log(error) {
72 const key = error.message;
73 if (this.errors.has(key)) {
74 this.errors.get(key).count++;
75 } else {
76 this.errors.set(key, {
77 message: error.message,
78 count: 1,
79 firstSeen: Date.now(),
80 lastSeen: Date.now()
81 });
82 }
83 }
84
85 getSummary() {
86 return Array.from(this.errors.values());
87 }
88}
89
90const aggregator = new ErrorAggregator();
91aggregator.log(new Error('Network error'));
92aggregator.log(new Error('Network error'));
93console.log('Summary:', aggregator.getSummary());

Sample Output

firstSeen: 1705314645123,

This is a timestamp, the milliseconds since 1 January 1970. Your run shows your own time.

lastSeen: 1705314645123

It matches firstSeen because the code never updates lastSeen on a repeat.

In this one

  • What fields a useful error log needs
  • Why structured JSON logs are easy to search
  • How log levels sort entries by how serious they are
  • How to count repeated errors with a Map

How it works

  1. 1

    ErrorLogger turns the error into a JSON entry.

  2. 2

    console.error prints the entry.

  3. 3

    The aggregator logs Network error twice.

  4. 4

    The second call adds one to the count.

  5. 5

    getSummary prints the grouped list.

Edge cases

Unknown level name

logger.log(err, "fatal") crashes because console.fatal does not exist.

Map fatal to console.error before calling.

Logging private data

Passwords end up in the log.

Remove secret fields before saving.

Same message, different cause

Two bugs share one message and get counted together.

Group by name and message, or by stack.

What's going on

A log is a saved record of what happened in a program. When an app breaks for a user, logs are often your only clue. Good error logs in JavaScript include the message, the stack and the time, in a format a computer can search.

Method 1 builds a log entry object and prints it as JSON with two-space indent. It uses console[level], which picks a console method by name. With level 'error' that is console.error. Be careful: there is no console.fatal, so console['fatal'] would be undefined and calling it would crash.

Method 2 is structured logging. Structured means each entry has the same fields in the same shape. It adds metadata, like a user id, and an environment name. It prints one line of JSON, which log tools can read easily.

Method 3 adds log levels: debug, info, warn, error and fatal. A level says how serious the entry is. Only error and fatal entries keep the stack, because that is when you need it most. This saves space for small messages.

Method 4 is an aggregator. It groups errors by message in a Map, a key and value store. The first time a message appears it saves count 1 and the time. Each repeat adds one to count. So instead of 1,000 copies of the same error, you see one entry with count 1000.

Note that lastSeen is never updated in this sample. Add entry.lastSeen = Date.now() inside the repeat branch if you need it. Methods 2 and 3 are defined but not called.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does console["error"](x) do?

Pick an answer to check it.

Question 2

In Method 3, which levels keep the stack?

Pick an answer to check it.

Questions people ask

Why log as JSON?

Log tools can filter JSON by field, like level or user id.

Should I log in production?

Yes, but send logs to a service, not only to the console.

What is a stack?

The list of function calls that led to the error, with file and line numbers.