In this lesson, you will learn how to shift from human-readable strings to machine-readable JSON objects to ensure your logs can be parsed, filtered, and analyzed by modern observability platforms.
When we use console.log('User logged in: ' + userId), we create "unstructured" data. While easy for a human to read in a terminal, it is a nightmare for log aggregators (like ELK, Datadog, or Splunk). To make sense of that string, an automated system must use complex Regular Expressions to extract the userId. If you ever change the phrasing of that string, your downstream analytics will break immediately.
Structured logging solves this by emitting a JSON object. This allows tools to ingest the log as a data structure, treating keys as searchable fields.
Implementing Structured Logs
Instead of concatenating strings, treat your logs as objects containing context:
const log = (level, message, context = {}) => {
const entry = {
timestamp: new Date().toISOString(),
level,
message,
...context
};
process.stdout.write(JSON.stringify(entry) + '\n');
};
// Usage
log('info', 'User login attempt', { userId: '123', ip: '192.168.1.1' });
The output becomes:
{"timestamp":"2023-10-27T10:00:00Z","level":"info","message":"User login attempt","userId":"123","ip":"192.168.1.1"}
Why This Matters for Observability
By keeping the schema consistent, you empower your infrastructure to perform powerful tasks that aren't possible with plain text. You can instantly run a query like "count all info logs where userId is 123" without any parsing overhead. This is the cornerstone of production-grade observability; it allows your logging pipeline to treat logs as data rather than just passive diagnostic text.
As you progress in your observability journey, remember that the goal is to make your logs a queryable database of your application's behavior. By adopting JSON-based logging now, you ensure that your production data is ready for the sophisticated monitoring and alerting tools you'll be building in the future.
Key Takeaway: Structured logging replaces brittle text strings with predictable JSON objects, transforming your logs from opaque messages into a queryable data source for downstream analysis.