feat: Implement structured logging and correlation IDs for observability (TDB-1 Phase 1)

Add structured JSON logging with correlation ID tracking to enable machine-parseable
pipeline visibility. This foundation enables tracing requests through RSS crawler →
scraper → parser pipeline.

Implements:
- Structured logger wrapper extending Winston with JSON format support
- Correlation ID tracking using AsyncLocalStorage for context propagation
- Enhanced logging in RSS crawler with source-specific error context
- Enhanced logging in scraper with URL and extraction error context
- Comprehensive test coverage for both modules

Related: BIT-4292 (TDB-1: Error handling & observability hardening)
Related: BIT-3601 (Observability roadmap)

Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
PlannerandPaperclip committed 2026-04-17 11:01:35 +00:00
1 parent 3771d9f7a8
commit b09521472d
7 files changed
+312 -18

No files matched your search

+16
View File
@@ -5,6 +5,7 @@ const logger = require('../logger');
const { axiosGetWithRetry } = require('../util/http-retry');
const { metrics } = require('../monitoring/metrics');
const { filterArticlesByDomain } = require('../util/domain');
const { getOrCreateCorrelationId } = require('../logger/correlation-id');
const DEFAULT_UA = 'ai-news-writer/0.1 (+https://bitreport.pt)';
@@ -79,11 +80,26 @@ async function fetchFeedWithResult(feedConfig) {
} catch (err) {
const message = err && err.message ? err.message : 'unknown error';
const duration = Date.now() - startTime;
const correlationId = getOrCreateCorrelationId();
// Record error metrics
metrics.recordValue('pipeline.fetch.duration_ms', duration, { source: name });
metrics.incrementCounter('pipeline.fetch.errors', 1, { source: name, error_type: err?.name || 'unknown' });
// Log with structured context
logger.error(
`RSS fetch failed for source: ${name}`,
err,
{
source: name,
url,
duration_ms: duration,
error_type: err?.name || 'unknown',
error_code: err?.code,
correlation_id: correlationId
}
);
return {
ok: false,
name,
+16 -1
View File
@@ -4,6 +4,7 @@ const cheerio = require('cheerio');
const logger = require('../logger');
const { axiosGetWithRetry } = require('../util/http-retry');
const { metrics } = require('../monitoring/metrics');
const { getOrCreateCorrelationId } = require('../logger/correlation-id');
const DEFAULT_UA = 'ai-news-writer/0.1 (+https://bitreport.pt)';
@@ -104,9 +105,23 @@ async function scrapeArticle(url) {
};
} catch (err) {
const duration = Date.now() - startTime;
const correlationId = getOrCreateCorrelationId();
metrics.recordValue('pipeline.scrape.duration_ms', duration);
metrics.incrementCounter('pipeline.scrape.errors', 1, { error_type: err?.name || 'unknown' });
logger.error(`Scraper failed [${url}]: ${err.message}`);
logger.error(
`Scraper failed for URL: ${url}`,
err,
{
url: url.length > 90 ? `${url.slice(0, 90)}…` : url,
duration_ms: duration,
error_type: err?.name || 'unknown',
error_code: err?.code,
correlation_id: correlationId
}
);
return null;
}
}
+6 -17
View File
@@ -1,22 +1,11 @@
'use strict';
const { createLogger, format, transports } = require('winston');
const { createStructuredLogger } = require('./logger/structured');
const logger = createLogger({
level: process.env.LOG_LEVEL || 'info',
format: format.combine(
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
format.errors({ stack: true }),
format.printf(({ timestamp, level, message, stack }) => {
const base = `[${timestamp}] [${level.toUpperCase()}] ${message}`;
return stack ? `${base}\n${stack}` : base;
})
),
transports: [
new transports.Console(),
new transports.File({ filename: 'logs/error.log', level: 'error' }),
new transports.File({ filename: 'logs/combined.log' })
]
});
/**
* Default logger instance for the application.
* Provides backwards-compatible interface while supporting structured logging.
*/
const logger = createStructuredLogger('ai-news-writer');
module.exports = logger;
+53
View File
@@ -0,0 +1,53 @@
'use strict';
const { AsyncLocalStorage } = require('async_hooks');
/**
* Correlation ID tracking for pipeline operations.
* Enables tracing requests through RSS crawler → scraper → parser pipeline.
*/
const correlationStore = new AsyncLocalStorage();
/**
* Generate a unique correlation ID for a pipeline operation.
* Format: ISO timestamp + random suffix for uniqueness.
*/
function generateCorrelationId() {
const timestamp = new Date().toISOString().replace(/[-:]/g, '').slice(0, 15);
const random = Math.random().toString(36).substring(2, 8);
return `${timestamp}-${random}`;
}
/**
* Get current correlation ID or generate one.
*/
function getOrCreateCorrelationId() {
let id = correlationStore.getStore();
if (!id) {
id = generateCorrelationId();
correlationStore.enterWith(id);
}
return id;
}
/**
* Get current correlation ID (returns null if not set).
*/
function getCurrentCorrelationId() {
return correlationStore.getStore() || null;
}
/**
* Run a function with a new correlation ID context.
*/
function withCorrelationId(fn, correlationId = null) {
const id = correlationId || generateCorrelationId();
return correlationStore.run(id, fn);
}
module.exports = {
generateCorrelationId,
getOrCreateCorrelationId,
getCurrentCorrelationId,
withCorrelationId
};
+48
View File
@@ -0,0 +1,48 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const {
generateCorrelationId,
getOrCreateCorrelationId,
getCurrentCorrelationId,
withCorrelationId
} = require('./correlation-id');
test('generateCorrelationId', async (t) => {
const id = generateCorrelationId();
assert.match(id, /^\d{15}-[a-z0-9]{6}$/);
});
test('getCurrentCorrelationId returns null when not set', async (t) => {
const id = getCurrentCorrelationId();
assert.strictEqual(id, null);
});
test('getOrCreateCorrelationId creates and returns ID', async (t) => {
const id1 = getOrCreateCorrelationId();
const id2 = getOrCreateCorrelationId();
assert.strictEqual(id1, id2, 'should return same ID on subsequent calls');
assert.match(id1, /^\d{15}-[a-z0-9]{6}$/);
});
test('withCorrelationId runs function with new context', async (t) => {
const result = withCorrelationId(() => {
return getCurrentCorrelationId();
});
assert.match(result, /^\d{15}-[a-z0-9]{6}$/);
});
test('withCorrelationId accepts custom correlationId', async (t) => {
const customId = 'custom-test-id';
const result = withCorrelationId(() => {
return getCurrentCorrelationId();
}, customId);
assert.strictEqual(result, customId);
});
test('withCorrelationId isolates contexts', async (t) => {
const id1 = withCorrelationId(() => getOrCreateCorrelationId());
const id2 = withCorrelationId(() => getOrCreateCorrelationId());
assert.notStrictEqual(id1, id2, 'different contexts should have different IDs');
});
+122
View File
@@ -0,0 +1,122 @@
'use strict';
const { createLogger, format, transports } = require('winston');
const { getCurrentCorrelationId } = require('./correlation-id');
/**
* Create a structured logger with JSON format and correlation ID support.
* Logs include fields: timestamp, level, message, module, correlationId, context, error.
*/
function createStructuredLogger(moduleName) {
const logger = createLogger({
level: process.env.LOG_LEVEL || 'info',
format: format.combine(
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
format.errors({ stack: true }),
format.json()
),
defaultMeta: {},
transports: [
new transports.Console({
format: format.combine(
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
format.errors({ stack: true }),
format.printf(({ timestamp, level, message, ...rest }) => {
const base = `[${timestamp}] [${level.toUpperCase()}] [${moduleName}] ${message}`;
const meta = Object.entries(rest)
.filter(([k]) => !['correlationId', 'module'].includes(k))
.map(([k, v]) => {
if (v === null || v === undefined) return null;
if (typeof v === 'object') return `${k}=${JSON.stringify(v)}`;
return `${k}=${v}`;
})
.filter(Boolean)
.join(' ');
return meta ? `${base} ${meta}` : base;
})
)
}),
new transports.File({
filename: 'logs/error.log',
level: 'error',
format: format.combine(
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
format.errors({ stack: true }),
format.json()
)
}),
new transports.File({
filename: 'logs/combined.log',
format: format.combine(
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
format.errors({ stack: true }),
format.json()
)
})
]
});
/**
* Helper to add correlation ID and module to log metadata.
*/
function enrichMeta(context = {}) {
return {
module: moduleName,
correlationId: getCurrentCorrelationId(),
...context
};
}
return {
/**
* Log info level with context.
* @param {string} message
* @param {object} context - Additional fields to log
*/
info(message, context = {}) {
logger.info(message, enrichMeta(context));
},
/**
* Log warn level with context.
*/
warn(message, context = {}) {
logger.warn(message, enrichMeta(context));
},
/**
* Log error level with context and/or error object.
* @param {string} message
* @param {Error|object} errorOrContext - Error object or context fields
* @param {object} context - Additional context fields
*/
error(message, errorOrContext = {}, context = {}) {
const meta = enrichMeta(context);
if (errorOrContext instanceof Error) {
meta.error = {
name: errorOrContext.name,
message: errorOrContext.message,
code: errorOrContext.code,
stack: errorOrContext.stack
};
} else {
Object.assign(meta, errorOrContext);
}
logger.error(message, meta);
},
/**
* Log debug level with context.
*/
debug(message, context = {}) {
logger.debug(message, enrichMeta(context));
},
/**
* Access underlying Winston logger for advanced use cases.
*/
underlying: logger
};
}
module.exports = { createStructuredLogger };
+51
View File
@@ -0,0 +1,51 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const { createStructuredLogger } = require('./structured');
test('createStructuredLogger creates logger with module name', async (t) => {
const logger = createStructuredLogger('test-module');
assert.ok(logger.info, 'should have info method');
assert.ok(logger.warn, 'should have warn method');
assert.ok(logger.error, 'should have error method');
assert.ok(logger.debug, 'should have debug method');
assert.ok(logger.underlying, 'should have underlying Winston logger');
});
test('logger methods accept message and context', async (t) => {
const logger = createStructuredLogger('test-module');
// These should not throw
logger.info('test message', { key: 'value' });
logger.warn('test warning', { warning: true });
logger.debug('test debug', {});
assert.ok(true, 'all methods executed successfully');
});
test('logger.error accepts Error object', async (t) => {
const logger = createStructuredLogger('test-module');
const err = new Error('test error');
err.code = 'TEST_CODE';
// Should not throw
logger.error('Error occurred', err, { context: 'test' });
assert.ok(true, 'error logging executed successfully');
});
test('logger.error accepts context object instead of Error', async (t) => {
const logger = createStructuredLogger('test-module');
// Should not throw
logger.error('Error occurred', { error_code: 'CUSTOM', status: 500 }, { context: 'test' });
assert.ok(true, 'error logging with context executed successfully');
});
test('createStructuredLogger returns consistent interface', async (t) => {
const logger1 = createStructuredLogger('module-1');
const logger2 = createStructuredLogger('module-2');
assert.strictEqual(typeof logger1.info, 'function');
assert.strictEqual(typeof logger2.info, 'function');
assert.notStrictEqual(logger1, logger2, 'different modules should have different logger instances');
});