GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — lib: added logger api to node core by mertcanaltin · Pull Request #60468 · nodejs/node

lib: added logger api to node core #60468

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
mertcanaltin wants to merge 31 commits into nodejs:main from mertcanaltin:mert/create-logger-api/node-core

Uh oh!

There was an error while loading. Please reload this page.

Closed

lib: added logger api to node core #60468

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
179e2d1
lib: add logger api in node core
mertcanaltin Feb 26, 2026
c658b21
lib: address review feedback for logger API
mertcanaltin Feb 26, 2026
a8603fb
lib: address review feedback for logger API
mertcanaltin Feb 26, 2026
95089ef
added missing test
mertcanaltin Feb 26, 2026
8be7bcf
logger: address review feedback
mertcanaltin Feb 27, 2026
c9282ef
logger: address review feedback
mertcanaltin Feb 27, 2026
04ec44c
Update lib/internal/logger/serializers.js
mertcanaltin Feb 27, 2026
4b361f7
delete pino benchmark
mertcanaltin Feb 27, 2026
b900393
delete exports (LEVELS, channels)
mertcanaltin Feb 27, 2026
36b1edd
edited logger api md
mertcanaltin Mar 29, 2026
14b0a3a
address review feedback for logger api
mertcanaltin Apr 5, 2026
87cbfa1
logger: skip input validation when no subscribers
mertcanaltin Apr 15, 2026
1f897fc
doc: address review feedback on logger.md
mertcanaltin Apr 15, 2026
3c24799
doc: add log channels in diagnostics_channel
mertcanaltin Apr 15, 2026
e58be5f
Update serializers.js
mertcanaltin Apr 15, 2026
4563bc2
Update serializers.js
mertcanaltin Apr 15, 2026
b4ceb0a
Update logger.js
mertcanaltin Apr 15, 2026
3e8166d
Update lib/internal/logger/serializers.js
mertcanaltin Apr 15, 2026
796f6b3
Merge branch 'main' into mert/create-logger-api/node-core
mertcanaltin Apr 19, 2026
700566b
logger: address review feedback
mertcanaltin Apr 19, 2026
42ae3a8
Merge branch 'main' into mert/create-logger-api/node-core
mertcanaltin Apr 20, 2026
b686bee
src: remove duplicate experimental_stream_iter
mertcanaltin Apr 22, 2026
d4f75da
Merge branch 'main' into mert/create-logger-api/node-core
mertcanaltin May 26, 2026
2e64414
use single diagnostics channel with consumer-side filtering
mertcanaltin Jun 27, 2026
98f3e5a
updated doc
mertcanaltin Jun 27, 2026
8ddfad1
apply serializers to bindings in Logger constructor
mertcanaltin Jun 27, 2026
dfe69ff
remove double serialize
mertcanaltin Jun 28, 2026
1108c7e
simplify bindings handling in child logger creation
mertcanaltin Jun 28, 2026
f38c709
add default error serializers to logger class
mertcanaltin Jun 28, 2026
9641dc6
Merge branch 'main' into mert/create-logger-api/node-core
mertcanaltin Aug 13, 2026
1a1c110
doc: regenerate node.1
mertcanaltin Aug 13, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Prev Previous commit
Next Next commit
use single diagnostics channel with consumer-side filtering
Signed-off-by: Mert Can Altin <[email protected]>
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@mertcanaltin
mertcanaltin committed Jun 27, 2026
commit 2e64414ce7666480d1080f98c1efb5811399b483

Some comments aren't visible on the classic Files Changed page.

There are no files selected for viewing

113 changes: 57 additions & 56 deletions 113 lib/logger.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const {
ObjectAssign,
ObjectDefineProperty,
ObjectKeys,
SafeWeakMap,
SymbolFor,
} = primordials;

Expand Down Expand Up @@ -38,17 +39,6 @@ const { emitExperimentalWarning, kEmptyObject } = require('internal/util');
emitExperimentalWarning('Logger');
const stdSerializers = require('internal/logger/serializers');

// Create channels for each log level
const channels = {
__proto__: null,
trace: diagnosticsChannel.channel('log:trace'),
debug: diagnosticsChannel.channel('log:debug'),
info: diagnosticsChannel.channel('log:info'),
warn: diagnosticsChannel.channel('log:warn'),
error: diagnosticsChannel.channel('log:error'),
fatal: diagnosticsChannel.channel('log:fatal'),
};

/*
* RFC5424 numerical ordering + log4j interface
* @link https://www.rfc-editor.org/rfc/rfc5424.html
Expand All @@ -63,6 +53,8 @@ const LEVELS = {
fatal: 60,
};

const channel = diagnosticsChannel.channel('log');

const LEVEL_NAMES = ObjectKeys(LEVELS);

function isReservedKey(key) {
Expand All @@ -79,15 +71,15 @@ function noop() {}
class LogConsumer {
/** @type {number} */
#levelValue;
Comment thread
mertcanaltin marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

#handlers;
#handler;
#attached;

constructor(options = kEmptyObject) {
validateObject(options, 'options');
const { level = 'info' } = options;
validateOneOf(level, 'options.level', LEVEL_NAMES);
this.#levelValue = LEVELS[level];
this.#handlers = { __proto__: null };
this.#handler = undefined;
this.#attached = false;

// Setup level-specific enabled properties for typo safety
Expand All @@ -100,20 +92,20 @@ class LogConsumer {
}

/**
* Attach this consumer to log channels
* Attach this consumer to log channel
*/
attach() {
if (this.#attached) {
return;
}
this.#attached = true;
for (const level of LEVEL_NAMES) {
if (this[level].enabled) {
const handler = this.handle.bind(this);
this.#handlers[level] = handler;
channels[level].subscribe(handler);
this.#handler = (record) => {
if (record.levelValue < this.#levelValue) {
return;
}
}
this.handle(record);
};
channel.subscribe(this.#handler);
}
Comment thread
mertcanaltin marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.


/**
Expand All @@ -124,12 +116,8 @@ class LogConsumer {
return;
}
this.#attached = false;
for (const level of LEVEL_NAMES) {
if (this.#handlers[level]) {
channels[level].unsubscribe(this.#handlers[level]);
this.#handlers[level] = undefined;
}
}
channel.unsubscribe(this.#handler);
this.#handler = undefined;
}
Comment thread
mertcanaltin marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.


/**
Expand All @@ -147,6 +135,7 @@ class LogConsumer {
class JSONConsumer extends LogConsumer {
Comment thread

@Qard Qard Feb 4, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we should have a Utf8StreamConsumer class between these two in order to make all that stream handling stuff reusable for other custom consumers. 🤔

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@mertcanaltin mertcanaltin Feb 5, 2026

Copy link
Copy Markdown
Member Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense. Will defer to a follow-up PR when we add more stream-based consumers.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
#stream;
#fields;
#bindingsCache;

constructor(options = kEmptyObject) {
Comment thread
mertcanaltin marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

super(options);
Expand All @@ -160,6 +149,7 @@ class JSONConsumer extends LogConsumer {
this.#stream = stream ? this.#createStream(stream) :
new Utf8Stream({ fd: 1 });
this.#fields = fields;
this.#bindingsCache = new SafeWeakMap();
}

#createStream(stream) {
Expand Down Expand Up @@ -199,6 +189,10 @@ class JSONConsumer extends LogConsumer {
// record.level is trusted internal value, record.msg is user input and must be escaped
let json = `{"level":"${record.level}","time":${record.time},"msg":${JSONStringify(record.msg)}`;

if (record.name !== undefined) {
json += `,${JSONStringify('name')}:${JSONStringify(record.name)}`;
}

const consumerFields = this.#fields;
const consumerKeys = ObjectKeys(consumerFields);
for (let i = 0; i < consumerKeys.length; i++) {
Expand All @@ -209,8 +203,8 @@ class JSONConsumer extends LogConsumer {
json += `,${JSONStringify(key)}:${JSONStringify(value)}`;
}

// Add pre-serialized bindings
json += record.bindingsStr;
// Add bindings, cached per bindings object to avoid rebuilding on every log
json += this.#serializeBindings(record.bindings);

// Add log fields
const fields = record.fields;
Expand All @@ -227,6 +221,30 @@ class JSONConsumer extends LogConsumer {
this.#stream.write(json);
}

#serializeBindings(bindings) {
if (!bindings || typeof bindings !== 'object') {
return '';
}

const cached = this.#bindingsCache.get(bindings);
if (cached !== undefined) {
return cached;
}

let result = '';
const keys = ObjectKeys(bindings);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (isReservedKey(key)) continue;
const value = bindings[key];
if (value === undefined) continue;
result += `,${JSONStringify(key)}:${JSONStringify(value)}`;
}

this.#bindingsCache.set(bindings, result);
return result;
}

/**
* Flush pending writes
* @param {Function} callback
Expand Down Expand Up @@ -259,26 +277,32 @@ class Logger {
#level;
#levelValue;
#bindings;
#bindingsStr; // Pre-serialized bindings JSON string
#name;
#serializers;

/**
* Create a new Logger instance
* @param {object} [options]
* @param {string} [options.level] - Minimum log level (default: 'info')
* @param {string} [options.name] - Optional logger name/namespace
* @param {object} [options.bindings] - Context fields (default: {})
* @param {object} [options.serializers] - Custom serializers (default: {})
*/
constructor(options = kEmptyObject) {
validateObject(options, 'options');
const {
level = 'info',
name,
bindings = kEmptyObject,
serializers = kEmptyObject,
} = options;

validateOneOf(level, 'options.level', LEVEL_NAMES);

if (name !== undefined) {
validateString(name, 'options.name');
}

validateObject(bindings, 'options.bindings');
validateObject(serializers, 'options.serializers');

Expand All @@ -290,6 +314,7 @@ class Logger {

this.#level = level;
this.#levelValue = LEVELS[level];
this.#name = name;
this.#bindings = bindings;

// Create serializers object with default err serializer
Expand All @@ -302,35 +327,10 @@ class Logger {
this.#serializers[key] = serializers[key];
}

// Pre-serialize bindings
this.#bindingsStr = this.#serializeBindings(bindings);

this.#setLogMethods();
}

/**
* Pre-serialize bindings
* @param {object} bindings - Context fields to serialize
* @returns {string} Pre-serialized bindings as JSON string
* @private
*/
#serializeBindings(bindings) {
if (!bindings || typeof bindings !== 'object') {
return '';
}

let result = '';
const keys = ObjectKeys(bindings);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (isReservedKey(key)) continue;
const serialized = this.#serializeValue(bindings[key], key);
if (serialized === undefined) continue;
result += `,${JSONStringify(key)}:${JSONStringify(serialized)}`;
}
return result;
}

/**
* Setup log methods with enabled getters.
*
Expand Down Expand Up @@ -502,7 +502,6 @@ class Logger {
return;
}
Comment thread
mertcanaltin marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.


const channel = channels[level];
if (!channel.hasSubscribers) {
return;
}
Expand Down Expand Up @@ -557,9 +556,11 @@ class Logger {
const record = {
Comment thread
mertcanaltin marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

__proto__: null,
level,
levelValue,
name: this.#name,
msg,
time: DateNow(),
bindingsStr: this.#bindingsStr, // Pre-serialized bindings string
bindings: this.#bindings,
fields: logFields,
};

Expand Down
16 changes: 16 additions & 0 deletions 16 test/parallel/test-log-basic.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,22 @@ describe('JSONConsumer', () => {
assert.strictEqual(log.userId, 123);
assert.strictEqual(typeof log.time, 'number');
});

it('should include logger name when provided', () => {
const stream = new TestStream();
const consumer = new JSONConsumer({ stream, level: 'info' });
consumer.attach();
const logger = new Logger({ level: 'info', name: 'api' });

logger.info({ msg: 'named logger', userId: 123 });
consumer.flushSync();

assert.strictEqual(stream.logs.length, 1);
const log = stream.logs[0];
assert.strictEqual(log.name, 'api');
assert.strictEqual(log.msg, 'named logger');
assert.strictEqual(log.userId, 123);
});
});

describe('additional fields', () => {
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.