MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Logging Architecture & Structured Log Levels0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
16.1Performance API (performance.mark & measure)16.2Logging Architecture & Structured Log Levels16.3Integrating Error Tracking (Sentry/Monitoring Concepts)16.4Crash Reporting & Telemetry Buffering
HomeTutorialsJavaScript for AdvancedLogging Architecture & Structured Log Levels
Integrating Error Tracking (Sentry/Monitoring Concepts)

Logging Architecture & Structured Log Levels

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

Relying on scattered console.log() calls across an enterprise application produces unreadable, unstructured logs that cannot be indexed or filtered in log aggregation platforms (Datadog, Splunk, ElasticSearch). Implementing a Structured Logging Architecture with formal Log Levels is critical for observability and production monitoring.


1. The Standard Log Levels Hierarchy

In production logging standards (RFC 5424 / Syslog / Winston), log levels follow a strict numerical severity hierarchy:

1 0: TRACE / DEBUG ──► Verbose internal variable states and function inputs
2 1: INFO ──► General application lifecycle events (server started, user logged in)
3 2: WARN ──► Recoverable anomalies (cache miss, deprecated API usage)
4 3: ERROR ──► Action failed, but application continues (DB query failed)
5 4: FATAL ──► Unrecoverable crash requiring immediate process termination

2. Structured JSON Logging

In production, logs must never be raw unstructured strings like "User 42 logged in at 10:00". They must be valid JSON objects with standardized fields:

1{
2 "timestamp": "2026-03-15T14:32:01.892Z",
3 "level": "INFO",
4 "service": "billing-service",
5 "environment": "production",
6 "traceId": "c8942a-991f",
7 "userId": "USR-1049",
8 "message": "Payment processed successfully",
9 "metadata": {
10 "amount": 120.00,
11 "currency": "USD",
12 "gatewayLatencyMs": 142
13 }
14}

3. Implementing a Production-Grade Logger Class

1const LogLevel = {
2 DEBUG: 0,
3 INFO: 1,
4 WARN: 2,
5 ERROR: 3,
6 FATAL: 4
7};
8 
9class Logger {
10 constructor(serviceName, minLevel = LogLevel.INFO) {
11 this.serviceName = serviceName;
12 this.minLevel = minLevel;
13 }
14 
15 setLevel(level) {
16 this.minLevel = level;
17 }
18 
19 #log(levelName, levelValue, message, meta = {}) {
20 // Suppress logs below active severity threshold
21 if (levelValue < this.minLevel) return;
22 
23 const logEntry = {
24 timestamp: new Date().toISOString(),
25 level: levelName,
26 service: this.serviceName,
27 message,
28 ...meta
29 };
30 
31 // Output as single-line JSON string (NDJSON format for Datadog / CloudWatch)
32 const jsonOutput = JSON.stringify(logEntry);
33 
34 if (levelValue >= LogLevel.ERROR) {
35 console.error(jsonOutput);
36 } else if (levelValue === LogLevel.WARN) {
37 console.warn(jsonOutput);
38 } else {
39 console.log(jsonOutput);
40 }
41 }
42 
43 debug(msg, meta) { this.#log('DEBUG', LogLevel.DEBUG, msg, meta); }
44 info(msg, meta) { this.#log('INFO', LogLevel.INFO, msg, meta); }
45 warn(msg, meta) { this.#log('WARN', LogLevel.WARN, msg, meta); }
46 error(msg, meta) { this.#log('ERROR', LogLevel.ERROR, msg, meta); }
47 fatal(msg, meta) { this.#log('FATAL', LogLevel.FATAL, msg, meta); }
48}
49 
50// Instantiate singleton service logger
51export const authLogger = new Logger('AuthService', process.env.NODE_ENV === 'production' ? LogLevel.INFO : LogLevel.DEBUG);

4. Context Enrichment & Trace Correlation

In microservices and distributed frontend apps, correlate logs across multiple API requests using a TraceId or CorrelationId:

1class ChildLogger {
2 constructor(parentLogger, contextualMetadata) {
3 this.parent = parentLogger;
4 this.context = contextualMetadata;
5 }
6 
7 info(msg, meta = {}) {
8 this.parent.info(msg, { ...this.context, ...meta });
9 }
10 
11 error(msg, meta = {}) {
12 this.parent.error(msg, { ...this.context, ...meta });
13 }
14}
15 
16// Create a child logger enriched with current HTTP request context:
17const requestLogger = new ChildLogger(authLogger, {
18 traceId: 'req_a9821f',
19 ip: '192.168.1.1'
20});
21 
22requestLogger.info('User authenticated successfully');
23// Automatically contains traceId, IP, and serviceName in JSON payload!

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the primary benefit of structured JSON logging over plain text strings?
Question 2
In an environment where the logging threshold is configured to WARN, which log levels will be emitted?
Question 3
What is a "Correlation ID" (or Trace ID) in distributed application logging?
Question 4
Why should DEBUG level logs be disabled in production environments?
Question 5
How does a Child Logger pattern simplify contextual logging?
Next Lesson

Integrating Error Tracking (Sentry/Monitoring Concepts)

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Performance API (performance.mark & measure)Integrating Error Tracking (Sentry/Monitoring Concepts)

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext