Skip to content

feat: add logger-plugin-console for enhanced console logging capabilities#2

Merged
tianyingchun merged 11 commits intohyperse-io:mainfrom
tclxshunquan-wang:feat/logger
Jul 2, 2025
Merged

feat: add logger-plugin-console for enhanced console logging capabilities#2
tianyingchun merged 11 commits intohyperse-io:mainfrom
tclxshunquan-wang:feat/logger

Conversation

@tclxshunquan-wang
Copy link
Contributor

@tclxshunquan-wang tclxshunquan-wang commented Jul 2, 2025

publish logger

Summary by CodeRabbit

  • New Features

    • Introduced a core logger module and two plugins for enhanced logging: one for standard output and one for console environments.
    • Added customizable formatting, color schemes, and advanced output options for log messages.
    • Provided comprehensive documentation and quick start guides for all new logging components.
  • Documentation

    • Rewrote and expanded README files for all logger packages with detailed usage instructions, configuration options, and feature descriptions.
  • Bug Fixes

    • Improved message formatting and color handling for consistent and readable log output.
  • Tests

    • Added extensive tests to verify logging behavior, formatting, and output across different scenarios.
  • Chores

    • Integrated new packages into the workspace and added build, lint, and test configurations for streamlined development.

@coderabbitai
Copy link

coderabbitai bot commented Jul 2, 2025

Warning

Rate limit exceeded

@tclxshunquan-wang has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 2 minutes and 53 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c0ef935 and 702aa9f.

📒 Files selected for processing (1)
  • packages/logger/src/constant/constant.ts (0 hunks)

Walkthrough

This change introduces a new logging infrastructure by adding three main components: a core logger module (@hyperse/logger), a standard output log plugin (@hyperse/logger-plugin-stdout), and a console log plugin (@hyperse/logger-plugin-console). It includes comprehensive documentation, configuration files, helper utilities, and test suites for both plugins, establishing a modular and extensible logging system.

Changes

File(s)/Path(s) Change Summary
.changeset/long-weeks-yawn.md, README.md Added/rewrote project-level documentation and summaries.
logger-mono.code-workspace Added logger-plugin-stdout to workspace and ESLint config.
packages/logger-plugin-console/README.md Added comprehensive documentation for the console plugin.
packages/logger-plugin-console/package.json Removed picocolors dependency, added @hyperse/ts-node to devDependencies.
packages/logger-plugin-console/src/constant.ts, src/types/type-options.ts, src/types/type-plugin.ts Changed color type definitions from arrays to CSS style strings; updated related types.
packages/logger-plugin-console/src/create-console-plugin.ts Fixed import path, improved error message, adjusted console output call.
packages/logger-plugin-console/src/helpers/helper-color-applier.ts Removed picocolors usage; simplified color logic to CSS style strings.
packages/logger-plugin-console/src/helpers/helper-format-message.ts, src/helpers/helper-format-stack.ts Simplified color application and formatting logic; removed terminal color for stack trace.
packages/logger-plugin-console/src/helpers/index.ts Added index file re-exporting all helpers.
packages/logger-plugin-console/tests/console-plugin.spec.ts, tests/console.ts Updated test descriptions and plugin configuration for enhanced output.
packages/logger-plugin-console/src/helpers/helper-assert-message.ts Simplified function signature and logic.
packages/logger-plugin-console/src/helpers/helper-format-time.ts Replaced hardcoded time values with named constants.
packages/logger-plugin-console/src/types/index.ts Removed export of unused color type.
packages/logger-plugin-stdout/* (all files) New package: Added all source, config, helper, type, test, and documentation files for the stdout logger plugin.
packages/logger-plugin-stdout/src/constant.ts, src/types/type-options.ts, src/types/type-plugin.ts Defined default colors, configuration, and types for the stdout plugin.
packages/logger-plugin-stdout/src/create-stdout-plugin.ts Implemented the stdout plugin factory with pipeline logic.
packages/logger-plugin-stdout/src/helpers/* Added helper utilities for message formatting, color application, stack trace, time formatting, loggability, merging options, and string padding.
packages/logger-plugin-stdout/tests/* Added tests and utilities for the stdout plugin.
packages/logger-plugin-stdout/package.json, tsconfig*.json, tsup.config.ts, vitest.config.ts, .gitignore, .vscode/*, LICENSE.md, CHANGELOG.md, lint-staged.config.mjs Added package metadata, build, lint, test, and environment configuration files.
packages/logger-plugin-stdout/index.js, src/index.ts, src/types/index.ts, src/helpers/index.ts Added barrel files for exports.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Logger
    participant Plugin (Console/Stdout)
    participant Formatter
    participant Output (Console/Stdout)

    User->>Logger: log(level, message)
    Logger->>Plugin (Console/Stdout): execute(level, message, context)
    Plugin (Console/Stdout)->>Formatter: formatMessage(options)
    Formatter-->>Plugin (Console/Stdout): formattedMessage
    Plugin (Console/Stdout)->>Output (Console/Stdout): write(formattedMessage)
Loading

Possibly related PRs

Poem

🐇
New logs now leap from stdout and screen,
With colors and configs, both subtle and keen.
Console and terminal, each with their say,
Formatting messages in a bright, clever way.
From helpers to tests, the system is stout—
This bunny is thrilled to log it all out!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 10

🧹 Nitpick comments (22)
packages/logger-plugin-std/.gitignore (1)

1-18: Consider consolidating ignore rules in the repo-level .gitignore to avoid duplication

Most of these patterns (dist/, build/, node_modules/, coverage/, etc.) are typically wanted for every package. Duplicating them in each package’s .gitignore means you’ll have to touch multiple files whenever a new rule is introduced or an existing one changes.
If the workspace already has a root .gitignore (or if you can add one), removing this file and relying on the root rules keeps maintenance overhead low and prevents rule drift.

packages/logger-plugin-std/LICENSE.md (1)

5-7: Minor grammar fix for clearer legal phrasing

The phrase “available under below licenses” is awkward and missing an article.
Consider wording it as “available under the following license:” (singular, because only one is listed).

-This software is available under below licenses:
-
-- Hyperse Commercial License (HCL)
+This software is available under the following license:
+
+- Hyperse Commercial License (HCL)
packages/logger-plugin-console/package.json (1)

3-3: Consider bumping the version.

If 0.0.1 was already published with the picocolors dependency, removing it is a breaking / behaviour-changing alteration; at minimum release 0.0.2 to keep semver monotonic.

Also applies to: 15-15

packages/logger-plugin-std/.vscode/settings.json (1)

1-3: Repo-wide VS Code settings are usually committed at the workspace root, not per-package .vscode/.

Having package-local editor settings can create noisy diffs and override individual developer preferences.
Move this to the root workspace settings or document the preference in README.md.

packages/logger-plugin-std/index.js (1)

1-1: Tiny proxy file could be generated by the build instead of checked-in.

Since index.js is a one-liner re-exporting the compiled output, you can:

  1. Point the "exports"."."."import" field directly at ./dist/index.js, or
  2. Generate this stub in the build step to avoid manual maintenance.
packages/logger-plugin-std/CHANGELOG.md (1)

1-1: Populate initial changelog entry.

The file only contains a header. Add at least a brief “0.0.1 – initial release” note so the changelog provides value.

packages/logger-plugin-std/tests/test-utils.ts (1)

1-5: Remove redundant await in return statement.

The await in the return statement is unnecessary since the function already returns a Promise.

export async function sleep(ms = 1000) {
-  return await new Promise<void>((resolver) => {
+  return new Promise<void>((resolver) => {
    setTimeout(resolver, ms);
  });
}
.changeset/long-weeks-yawn.md (1)

7-9: Consider enhancing the changeset description.

While the current description is functional, consider providing more detailed information about the new logging infrastructure for better release documentation.

-1、add logger
-2、add std log plugin
-3、add console log plugin
+Add comprehensive logging infrastructure:
+- Core logger module with plugin support
+- Standard output plugin for Node.js environments with rich formatting
+- Console plugin for browser/console logging with enhanced styling
packages/logger-plugin-std/lint-staged.config.mjs (1)

19-21: Minor documentation inconsistency.

The comment mentions disabling react-hooks/exhaustive-deps but the rules array is empty. Consider either removing the comment if the rule isn't applicable to this package, or adding the rule if it needs to be explicitly disabled.

      // when autofixing staged-files a good tip is to disable react-hooks/exhaustive-deps, cause
      // a change here can potentially break things without proper visibility.
-     rules: [],
+     rules: ['--rule', 'react-hooks/exhaustive-deps:off'],

Or remove the comment if not applicable:

-     // when autofixing staged-files a good tip is to disable react-hooks/exhaustive-deps, cause
-     // a change here can potentially break things without proper visibility.
      rules: [],
packages/logger-plugin-std/tests/std-plugin.spec.ts (1)

28-28: Consider reducing sleep duration for faster tests.

The 100ms sleep duration may be unnecessarily long for these tests, potentially slowing down the test suite execution.

Consider reducing the sleep duration:

- await sleep(100);
+ await sleep(10);

Alternatively, investigate if the sleep is necessary at all, as process.stdout.write is typically synchronous.

Also applies to: 43-43, 66-66, 89-89, 113-113, 143-143

packages/logger-plugin-std/src/helpers/helper-str-pad.ts (1)

6-29: Consider using native String.prototype.repeat instead of custom implementation.

While the custom repeat function includes good error handling, modern JavaScript environments support String.prototype.repeat natively, which would simplify the code and improve performance.

Consider replacing the custom implementation:

-const repeat = (str = '', count = 0) => {
-  if (count < 0) {
-    throw new RangeError('repeat count must be non-negative');
-  }
-  if (count === Infinity) {
-    throw new RangeError('repeat count must be less than infinity');
-  }
-  // floors and rounds-down it.
-  count = count | 0;
-  if (str.length === 0 || count === 0) {
-    return '';
-  }
-  // Ensuring count is a 31-bit integer allows us to heavily optimize the
-  // main part. But anyway, most current (August 2014) browsers can't handle
-  // strings 1 << 28 chars or longer, so:
-  if (str.length * count >= 1 << 28) {
-    throw new RangeError('repeat count must not overflow maximum string size');
-  }
-  const rpts: string[] = [];
-  for (let i = 0; i < count; i++) {
-    rpts.push(str);
-  }
-  return rpts.join('');
-};
+const repeat = (str = '', count = 0) => {
+  if (count < 0) {
+    throw new RangeError('repeat count must be non-negative');
+  }
+  if (count === Infinity) {
+    throw new RangeError('repeat count must be less than infinity');
+  }
+  return str.repeat(Math.floor(count));
+};

If keeping the custom implementation, consider documenting the bitwise OR operation purpose more clearly.

packages/logger-plugin-std/src/helpers/helper-format-message.ts (1)

12-146: Consider breaking down the complex formatting function.

While the logic is correct and comprehensive, this 134-line function handles multiple formatting concerns. Consider extracting smaller functions for better maintainability.

Potential extractions:

  • formatDateTime(time, options) for lines 47-82
  • formatContext(ctx, options) for lines 94-123
  • formatMessage(message, messageName, stack) for lines 130-143

This would improve readability and testability of individual formatting components.

README.md (1)

293-297: Add language specification to fenced code block.

The ASCII diagram should specify a language to satisfy linting requirements.

-```
+```text
 Log Message → Plugin 1 → Plugin 2 → ... → Plugin N → Output
      ↓           ↓         ↓              ↓
    Context    Context   Context       Context

</blockquote></details>
<details>
<summary>packages/logger-plugin-std/src/helpers/helper-format-time.ts (1)</summary><blockquote>

`9-12`: **Remove unused remainder assignment.**

The `remainder` variable is recalculated on line 12 but the original remainder from line 9 is never used. This creates unnecessary computation and potential confusion.



```diff
 const addUnitOfTime = (
   prefix: string,
   time: Date,
   lastTime: Date,
   colorFn: (s: string) => string,
   unitValueInMilliseconds: number,
   unitName: string
 ) => {
-  let remainder = time.getTime() - lastTime.getTime();
+  const timeDiff = time.getTime() - lastTime.getTime();
-  const unitCount = Math.floor(remainder / unitValueInMilliseconds);
+  const unitCount = Math.floor(timeDiff / unitValueInMilliseconds);

-  remainder = remainder % unitValueInMilliseconds;
   return unitCount !== 0
     ? colorFn(prefix + unitCount + unitName) + ' '
     : unitValueInMilliseconds === 1
       ? colorFn(prefix + '0') + ' '
       : '';
 };
packages/logger-plugin-console/README.md (4)

124-131: Add language specifiers to fenced code blocks.

Multiple fenced code blocks are missing language specifiers, which affects syntax highlighting and accessibility.

-```
+```console
 [ FATAL ] WHAT WILL I DO?!
 [ ERROR ] Something went wrong
 [ WARN ]  Warning message
 [ INFO ]  Information
 [ DEBUG ] Debug details
 [ VERBOSE ] Verbose information
-```
+```

248-248: Fix compound adjective hyphenation.

"Full Featured" should be hyphenated when used as a compound adjective.

-### Full Featured Configuration
+### Full-Featured Configuration

147-191: Add language specifiers to remaining example code blocks.

Several example output code blocks need language specifiers for better formatting.

Apply similar fixes to the remaining code blocks at lines:

  • 147-149: Add console language specifier
  • 159-161: Add console language specifier
  • 171-173: Add console language specifier
  • 177-179: Add console language specifier
  • 189-191: Add console language specifier

328-357: Add language specifiers to output example code blocks.

The output example code blocks should specify console as the language for proper formatting.

-```
+```console
 info message
-```
+```

Apply the same fix to all output example blocks (lines 334, 340, 346, 352).

packages/logger-plugin-std/README.md (4)

124-131: Add language specifiers to fenced code blocks.

Multiple fenced code blocks are missing language specifiers, affecting syntax highlighting.

-```
+```console
 [ FATAL ] WHAT WILL I DO?!
 [ ERROR ] Something went wrong
 [ WARN ]  Warning message
 [ INFO ]  Information
 [ DEBUG ] Debug details
 [ VERBOSE ] Verbose information
-```
+```

257-257: Fix compound adjective hyphenation.

"Full Featured" should be hyphenated when used as a compound adjective.

-### Full Featured Configuration
+### Full-Featured Configuration

219-225: Fix formatting issues in color list.

The available colors list has formatting inconsistencies flagged by static analysis.

The current formatting may cause rendering issues. Consider restructuring the color list with proper markdown formatting or using a table format for better readability.


147-191: Add language specifiers to example output blocks.

Several example output code blocks need language specifiers for proper formatting.

Apply console language specifiers to the code blocks at lines:

  • 147-149: Date example
  • 159-161: Timestamp example
  • 171-173: 24-hour clock example
  • 177-179: 12-hour clock example
  • 189-191: Arrow example
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e36e023 and 6ce5ee5.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (47)
  • .changeset/long-weeks-yawn.md (1 hunks)
  • README.md (1 hunks)
  • logger-mono.code-workspace (2 hunks)
  • packages/logger-plugin-console/README.md (1 hunks)
  • packages/logger-plugin-console/package.json (1 hunks)
  • packages/logger-plugin-console/src/constant.ts (1 hunks)
  • packages/logger-plugin-console/src/create-console-plugin.ts (2 hunks)
  • packages/logger-plugin-console/src/helpers/helper-color-applier.ts (1 hunks)
  • packages/logger-plugin-console/src/helpers/helper-format-message.ts (6 hunks)
  • packages/logger-plugin-console/src/helpers/helper-format-stack.ts (1 hunks)
  • packages/logger-plugin-console/src/types/index.ts (0 hunks)
  • packages/logger-plugin-console/src/types/type-options.ts (2 hunks)
  • packages/logger-plugin-console/src/types/type-plugin.ts (1 hunks)
  • packages/logger-plugin-console/tests/console-plugin.spec.ts (1 hunks)
  • packages/logger-plugin-console/tests/console.ts (1 hunks)
  • packages/logger-plugin-std/.gitignore (1 hunks)
  • packages/logger-plugin-std/.vscode/launch.json (1 hunks)
  • packages/logger-plugin-std/.vscode/settings.json (1 hunks)
  • packages/logger-plugin-std/CHANGELOG.md (1 hunks)
  • packages/logger-plugin-std/LICENSE.md (1 hunks)
  • packages/logger-plugin-std/README.md (1 hunks)
  • packages/logger-plugin-std/eslint.config.js (1 hunks)
  • packages/logger-plugin-std/index.js (1 hunks)
  • packages/logger-plugin-std/lint-staged.config.mjs (1 hunks)
  • packages/logger-plugin-std/package.json (1 hunks)
  • packages/logger-plugin-std/src/constant.ts (1 hunks)
  • packages/logger-plugin-std/src/create-std-plugin.ts (1 hunks)
  • packages/logger-plugin-std/src/helpers/helper-assert-message.ts (1 hunks)
  • packages/logger-plugin-std/src/helpers/helper-color-applier.ts (1 hunks)
  • packages/logger-plugin-std/src/helpers/helper-format-message.ts (1 hunks)
  • packages/logger-plugin-std/src/helpers/helper-format-stack.ts (1 hunks)
  • packages/logger-plugin-std/src/helpers/helper-format-time.ts (1 hunks)
  • packages/logger-plugin-std/src/helpers/helper-is-loggable.ts (1 hunks)
  • packages/logger-plugin-std/src/helpers/helper-merge-optons.ts (1 hunks)
  • packages/logger-plugin-std/src/helpers/helper-normalize-level.ts (1 hunks)
  • packages/logger-plugin-std/src/helpers/helper-str-pad.ts (1 hunks)
  • packages/logger-plugin-std/src/index.ts (1 hunks)
  • packages/logger-plugin-std/src/types/index.ts (1 hunks)
  • packages/logger-plugin-std/src/types/type-options.ts (1 hunks)
  • packages/logger-plugin-std/src/types/type-plugin.ts (1 hunks)
  • packages/logger-plugin-std/tests/std-plugin.spec.ts (1 hunks)
  • packages/logger-plugin-std/tests/std.ts (1 hunks)
  • packages/logger-plugin-std/tests/test-utils.ts (1 hunks)
  • packages/logger-plugin-std/tsconfig.build.json (1 hunks)
  • packages/logger-plugin-std/tsconfig.json (1 hunks)
  • packages/logger-plugin-std/tsup.config.ts (1 hunks)
  • packages/logger-plugin-std/vitest.config.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/logger-plugin-console/src/types/index.ts
🧰 Additional context used
🧬 Code Graph Analysis (13)
packages/logger-plugin-console/tests/console.ts (1)
packages/logger-plugin-console/src/create-console-plugin.ts (1)
  • createConsolePlugin (12-45)
packages/logger-plugin-std/src/helpers/helper-is-loggable.ts (2)
packages/logger/src/types/type-logger.ts (1)
  • LoggerContext (5-8)
packages/logger-plugin-std/src/types/type-plugin.ts (1)
  • StdPluginContext (4-4)
packages/logger-plugin-console/src/types/type-plugin.ts (2)
packages/logger/src/types/type-message.ts (1)
  • LoggerMessageObject (1-6)
packages/logger-plugin-std/src/types/type-plugin.ts (1)
  • LevelData (8-23)
packages/logger-plugin-std/src/types/type-options.ts (1)
packages/logger-plugin-std/src/types/type-color.ts (1)
  • Color (3-6)
packages/logger-plugin-std/tests/std.ts (3)
packages/logger/src/core/create-logger.ts (1)
  • createLogger (5-17)
packages/logger-plugin-std/src/create-std-plugin.ts (1)
  • createStdPlugin (12-52)
packages/logger/src/core/logger.ts (1)
  • error (155-161)
packages/logger-plugin-std/src/helpers/helper-assert-message.ts (1)
packages/logger/src/types/type-message.ts (1)
  • LoggerMessageObject (1-6)
packages/logger-plugin-std/src/create-std-plugin.ts (6)
packages/logger-plugin-std/src/helpers/helper-merge-optons.ts (1)
  • mergeStdOptions (5-9)
packages/logger/src/plugin/define-plugin.ts (1)
  • definePlugin (12-14)
packages/logger-plugin-std/src/types/type-plugin.ts (2)
  • StdPluginContext (4-4)
  • StdPluginMessage (6-6)
packages/logger-plugin-std/src/helpers/helper-is-loggable.ts (1)
  • isLoggable (4-9)
packages/logger-plugin-std/src/helpers/helper-assert-message.ts (1)
  • assertMessage (3-15)
packages/logger-plugin-std/src/helpers/helper-format-message.ts (1)
  • formatMessage (12-146)
packages/logger-plugin-std/src/types/type-plugin.ts (3)
packages/logger/src/types/type-message.ts (1)
  • LoggerMessageObject (1-6)
packages/logger-plugin-console/src/types/type-plugin.ts (1)
  • LevelData (7-22)
packages/logger-plugin-std/src/types/type-color.ts (1)
  • Color (3-6)
packages/logger-plugin-std/src/helpers/helper-format-stack.ts (1)
packages/logger-plugin-std/src/helpers/helper-color-applier.ts (1)
  • terminalColor (10-22)
packages/logger-plugin-console/src/helpers/helper-format-message.ts (4)
packages/logger-plugin-console/src/helpers/helper-normalize-level.ts (1)
  • normalizeLevelData (6-18)
packages/logger-plugin-console/src/helpers/helper-color-applier.ts (1)
  • colorApplier (7-9)
packages/logger-plugin-console/src/helpers/helper-str-pad.ts (1)
  • strTimePad (47-49)
packages/logger-plugin-console/src/helpers/helper-format-stack.ts (1)
  • formatStack (13-16)
packages/logger-plugin-std/tests/std-plugin.spec.ts (4)
packages/logger/src/core/create-logger.ts (1)
  • createLogger (5-17)
packages/logger-plugin-std/src/create-std-plugin.ts (1)
  • createStdPlugin (12-52)
packages/logger-plugin-std/tests/test-utils.ts (1)
  • sleep (1-5)
packages/logger/src/core/logger.ts (1)
  • error (155-161)
packages/logger-plugin-std/src/constant.ts (2)
packages/logger-plugin-std/src/types/type-color.ts (1)
  • Color (3-6)
packages/logger-plugin-std/src/types/type-options.ts (1)
  • StdOptions (4-129)
packages/logger-plugin-std/src/helpers/helper-color-applier.ts (1)
packages/logger-plugin-std/src/types/type-color.ts (1)
  • Color (3-6)
🪛 LanguageTool
packages/logger-plugin-std/LICENSE.md

[uncategorized] ~5-~5: You might be missing the article “the” here.
Context: ... Ltd) This software is available under below licenses: - Hyperse Commercial License...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

packages/logger-plugin-console/README.md

[uncategorized] ~248-~248: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...teConsolePlugin()) .build(); ### Full Featured Configuration typescript const logg...

(EN_COMPOUND_ADJECTIVE_INTERNAL)

packages/logger-plugin-std/README.md

[uncategorized] ~219-~219: Loose punctuation mark.
Context: ... ``` Available Colors: - 'black', `'red'`, `'green'`, `'yellow'`, `'blue'...

(UNLIKELY_OPENING_PUNCTUATION)


[typographical] ~221-~221: Two consecutive commas
Context: ...t', 'magentaBright', 'cyanBright', 'whiteBright'-'bgBlack', 'bgRed', 'bgGreen', 'bgYellow', ...

(DOUBLE_PUNCTUATION)


[typographical] ~222-~222: Two consecutive commas
Context: ... 'bgBlue', 'bgMagenta', 'bgCyan', 'bgWhite' - 'bgBlackBright', 'bgRedBright', 'bgGreenBright', `'b...

(DOUBLE_PUNCTUATION)


[typographical] ~223-~223: Two consecutive commas
Context: ... 'bgMagentaBright', 'bgCyanBright', 'bgWhiteBright' - 'bold', 'dim', 'italic', 'underline', `'i...

(DOUBLE_PUNCTUATION)


[uncategorized] ~257-~257: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...createStdPlugin()) .build(); ### Full Featured Configuration typescript const logg...

(EN_COMPOUND_ADJECTIVE_INTERNAL)


[uncategorized] ~337-~337: Possible missing comma found.
Context: ...lly detect if it's running in a Node.js environment and will exit gracefully with an error ...

(AI_HYDRA_LEO_MISSING_COMMA)

🪛 markdownlint-cli2 (0.17.2)
packages/logger-plugin-std/LICENSE.md

14-14: Bare URL used

(MD034, no-bare-urls)

packages/logger-plugin-console/README.md

124-124: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


147-147: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


159-159: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


171-171: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


177-177: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


189-189: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


328-328: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


334-334: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


340-340: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


346-346: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


352-352: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

README.md

293-293: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

packages/logger-plugin-std/README.md

124-124: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


147-147: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


159-159: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


171-171: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


177-177: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


189-189: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


298-298: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


304-304: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


310-310: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


316-316: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


322-322: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: deploy (20.x)
🔇 Additional comments (36)
packages/logger-plugin-std/LICENSE.md (1)

11-13: Verify correct legal entity name

The license first cites “Hyperse (Yuantai Information Technology (Shanghai) Co., Ltd)” but later references “Hyperse GmbH”.
If both entities are distinct, clarify their respective roles; otherwise, align the names to avoid legal ambiguity.

packages/logger-plugin-console/src/create-console-plugin.ts (2)

21-21: Minor text improvement looks good.

The error message is more grammatically correct with "This level is too low."


40-40: Spread operator correctly handles array-based output format.

The change from console.log(outputMessage) to console.log(...outputMessage) properly handles the new format where outputMessage is an array, enabling better console formatting with CSS styles.

packages/logger-plugin-console/src/helpers/helper-format-stack.ts (1)

15-15: Simplified stack formatting aligns with CSS styling refactor.

Removing the color application and using simple indentation is consistent with the broader move from ANSI colors to CSS-based console styling.

logger-mono.code-workspace (2)

11-14: Workspace folder configuration looks good.

Proper addition of the new logger-plugin-std package to the workspace folders.


75-75: ESLint working directory correctly added.

Adding the new package to ESLint working directories ensures proper linting coverage.

packages/logger-plugin-std/src/types/index.ts (1)

1-3: Clean barrel export pattern for types.

Standard TypeScript approach for providing a single entry point for type imports. Implementation is clean and follows best practices.

packages/logger-plugin-std/src/index.ts (1)

1-2: LGTM! Clean entry point consolidation.

The re-export pattern is well-executed and follows ES module conventions correctly with proper file extensions.

packages/logger-plugin-std/.vscode/launch.json (1)

1-18: LGTM! Proper VS Code debugging setup.

The launch configuration is correctly configured for debugging unit tests with appropriate exclusions and file targeting.

packages/logger-plugin-std/eslint.config.js (1)

1-10: LGTM! Appropriate ESLint configuration for logging library.

Disabling the no-explicit-any rule is reasonable for a logging library that needs to handle arbitrary message types flexibly.

packages/logger-plugin-std/src/helpers/helper-is-loggable.ts (1)

4-9: isLoggable helper comparison is correct

The LogLevel enum is defined as:

  • Error = 0
  • Warn = 1
  • Info = 2
  • Debug = 3
  • Verbose = 4

With thresholdLevel representing the minimum (most severe) level to log, the check

ctx.thresholdLevel >= level

(equivalently level <= thresholdLevel) correctly allows logging of any level at or above the configured threshold (e.g. setting thresholdLevel = LogLevel.Info logs Error, Warn, and Info). No changes are required.

packages/logger-plugin-std/src/helpers/helper-normalize-level.ts (1)

6-18: LGTM! Clean and well-structured helper function.

The implementation correctly handles color fallback using nullish coalescing, properly extracts the level name from the enum, and returns a well-structured object. The type annotations are accurate and the logic is sound.

packages/logger-plugin-std/vitest.config.ts (1)

4-16: LGTM! Standard and well-configured Vitest setup.

The configuration properly sets up the alias for local development, includes appropriate test patterns, and follows standard Vitest practices. The alias mapping to the logger source ensures proper resolution during testing.

packages/logger-plugin-console/tests/console.ts (2)

9-23: LGTM! Comprehensive plugin configuration for testing.

The console plugin configuration effectively demonstrates all available formatting options, providing excellent test coverage for the plugin's capabilities. The options are clearly structured and cover timestamp, naming, capitalization, and display preferences.


26-51: LGTM! Good test coverage of different logging scenarios.

The test cases effectively cover various logging patterns including simple string messages, structured object messages with prefixes and names, and proper error handling with stack traces. This provides comprehensive validation of the plugin's functionality.

packages/logger-plugin-std/tsconfig.build.json (1)

1-19: LGTM! Well-configured TypeScript build setup.

The build configuration follows best practices with proper source/output directory separation, appropriate exclusions, and modern module resolution. The single entry point inclusion is typical for library packages and the exclusions properly filter out development and build artifacts.

packages/logger-plugin-console/src/types/type-plugin.ts (2)

5-5: LGTM! Type alias simplification is appropriate.

The direct type alias to LoggerMessageObject removes unnecessary complexity and aligns with the console plugin's requirements.


11-11: LGTM! CSS-based color styling is appropriate for console output.

The change from Color[] to string aligns with using CSS style strings for browser console styling instead of terminal color codes, which is the correct approach for a console plugin.

packages/logger-plugin-std/tsconfig.json (1)

1-16: LGTM! Well-structured TypeScript configuration.

The configuration appropriately extends the base config, sets up path mapping for the core logger, and includes necessary compiler options for a plugin package.

packages/logger-plugin-std/src/helpers/helper-format-stack.ts (2)

3-13: LGTM! Robust stack trace parsing with proper validation.

The parseStack function correctly validates input, removes the error message line, and cleans up file URLs. The implementation handles edge cases well.


15-18: LGTM! Appropriate formatting with color and indentation.

The formatStack function properly applies red terminal coloring and indentation to create readable stack traces. The use of terminalColor is consistent with the std plugin's terminal output approach.

packages/logger-plugin-std/tsup.config.ts (1)

3-13: LGTM! Well-configured modern build setup.

The tsup configuration follows best practices with conditional optimization, ESM output, and proper TypeScript integration. The build setup is appropriate for a modern npm package.

packages/logger-plugin-std/tests/std.ts (1)

1-37: LGTM! Comprehensive test coverage.

The test file effectively demonstrates various usage patterns including string messages, structured messages with different log levels, and proper error handling. The code is clean and well-structured.

packages/logger-plugin-std/src/create-std-plugin.ts (1)

12-52: LGTM! Well-structured plugin implementation.

The plugin implementation follows excellent patterns:

  • Proper environment validation for Node.js
  • Clean pipeline architecture with logical separation of concerns
  • Appropriate error handling with early exits
  • Good use of helper functions for modularity

The async pipeline pattern effectively separates environment checks, message processing, formatting, and output operations.

packages/logger-plugin-std/tests/std-plugin.spec.ts (1)

131-141: LGTM! Good error handling test pattern.

The error creation and logging test properly demonstrates stack trace handling with try/catch and non-null assertion.

packages/logger-plugin-std/src/helpers/helper-str-pad.ts (1)

47-49: LGTM! Time padding utility is well-implemented.

The function correctly zero-pads time values to 2 digits using left padding.

packages/logger-plugin-std/src/types/type-plugin.ts (1)

1-23: LGTM! Well-structured type definitions.

The type definitions are clean and provide good type safety. The LevelData type using Color[] for colors is more type-safe than a simple string approach.

packages/logger-plugin-std/src/helpers/helper-format-message.ts (1)

64-78: LGTM! Solid time formatting logic with 12/24 hour support.

The time formatting correctly handles both 12-hour and 24-hour formats with proper AM/PM display and hour conversion logic.

packages/logger-plugin-std/src/helpers/helper-color-applier.ts (2)

10-22: LGTM! Well-implemented color application with proper fallbacks.

The function correctly handles the no-color case and applies multiple colors sequentially using Picocolors.


24-37: LGTM! Good separation of color types and decorations.

The filtering logic properly distinguishes between text colors and decorations (strikethrough, underline), enabling targeted styling application.

packages/logger-plugin-console/src/constant.ts (1)

4-14: Well-executed refactor to CSS-based styling.

The migration from Color[] arrays to CSS style strings is a clean architectural improvement that removes the picocolors dependency while maintaining styling capabilities through console CSS placeholders. The CSS syntax is correct and the approach is more lightweight.

packages/logger-plugin-std/src/constant.ts (1)

1-36: Well-structured constants module for the std plugin.

The implementation correctly defines comprehensive defaults for the standard logger plugin. The use of Color[] arrays (vs. CSS strings in the console plugin) is appropriate for terminal output via ANSI codes, while the console plugin uses CSS styling for browser compatibility.

packages/logger-plugin-console/src/helpers/helper-color-applier.ts (1)

7-9: Excellent simplification aligned with CSS styling approach.

The new colorApplier function is much cleaner and correctly uses %c markers for console CSS styling. This simplification removes complexity while maintaining the core functionality needed for the console plugin's CSS-based color system.

packages/logger-plugin-console/src/types/type-options.ts (1)

58-58: Type definitions properly updated for CSS styling.

The type changes from Color[] to string are consistent with the architectural refactor, and the updated JSDoc examples clearly demonstrate the expected CSS format. The date format example update to ISO format (YYYY-MM-DD) is also a good improvement.

Also applies to: 102-127

README.md (1)

1-325: Excellent comprehensive documentation.

The README transformation from minimal to comprehensive documentation is outstanding. It provides clear installation instructions, usage examples, plugin system explanation, and architectural overview. The structured approach with badges, code examples, and detailed sections makes this very user-friendly.

packages/logger-plugin-console/src/helpers/helper-format-message.ts (1)

148-152: Approve the CSS styling approach.

The implementation correctly handles the transition from ANSI colors to CSS styling for console output. The array return format with message and styles is appropriate for console.log usage.

Comment on lines 46 to 48
"dependencies": {
"@hyperse/logger": "workspace:*",
"picocolors": "^1.1.1"
"@hyperse/logger": "workspace:*"
},
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify that no code still imports picocolors.

picocolors has been removed from dependencies, but if any source or generated file still contains
import 'picocolors' the package will fail at runtime / build time.

If the command returns anything other than the package.json diff itself, add the package back or drop the leftover import.


🏁 Script executed:

#!/bin/bash
# Search for any residual imports of picocolors
rg -n "picocolors" --type ts --type js --type d.ts

Length of output: 79


I’ll broaden the search to include all relevant extensions and drop the unsupported --type d.ts flag:


🏁 Script executed:

#!/bin/bash
# Search for any residual imports or references to picocolors across common source file extensions
rg -n "picocolors" -g "*.ts" -g "*.tsx" -g "*.js" -g "*.jsx" -g "*.d.ts"

Length of output: 265


Action Required: Address remaining picocolors imports in logger-plugin-std

The removal of picocolors from the console plugin uncovered two residual imports in the std plugin. You must either restore picocolors as a dependency of packages/logger-plugin-std or remove/replace these imports:

• packages/logger-plugin-std/src/types/type-color.ts

import type colors from 'picocolors';

• packages/logger-plugin-std/src/helpers/helper-color-applier.ts

import Picocolors from 'picocolors';

Options:

  • Re-add "picocolors" (matching the version used elsewhere) to packages/logger-plugin-std/package.json under dependencies, then run install.
  • Refactor these files to remove or replace picocolors usage with your new color‐utility API.
🤖 Prompt for AI Agents
In packages/logger-plugin-std/package.json around lines 46 to 48, the plugin
still imports picocolors in two files but does not list it as a dependency. To
fix this, either add picocolors back to the dependencies in
packages/logger-plugin-std/package.json with the correct version and run the
install, or refactor the imports and usage of picocolors in
src/types/type-color.ts and src/helpers/helper-color-applier.ts to use the new
color utility API instead, removing all references to picocolors.

Comment on lines 5 to 9
export const mergeStdOptions = (
options: Partial<StdOptions> = {}
): Required<StdOptions> => {
return mergeOptions(defaultConfig, options);
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix the filename typo for consistency.

The filename contains a typo: helper-merge-optons.ts should be helper-merge-options.ts. This affects imports and overall code maintainability.

The function implementation itself is correct and appropriately uses the core logger's mergeOptions utility.

🤖 Prompt for AI Agents
In packages/logger-plugin-std/src/helpers/helper-merge-optons.ts lines 5 to 9,
the filename contains a typo "optons" instead of "options". Rename the file to
helper-merge-options.ts to fix the typo and ensure consistency in imports and
maintainability across the codebase.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/logger-plugin-console/src/helpers/helper-assert-message.ts (1)

7-11: Remove explicit undefined assignments for optional properties.

Since name and stack are optional in the LoggerMessageObject type, explicitly setting them to undefined is redundant. Also, consider whether the prefix property should be included for consistency with the type definition.

    return {
      message: message,
-      name: undefined,
-      stack: undefined,
    };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6ce5ee5 and b760ca5.

📒 Files selected for processing (8)
  • packages/logger-plugin-console/src/helpers/helper-assert-message.ts (1 hunks)
  • packages/logger-plugin-console/src/helpers/helper-format-time.ts (8 hunks)
  • packages/logger-plugin-console/tests/console-plugin.spec.ts (2 hunks)
  • packages/logger-plugin-std/src/create-std-plugin.ts (1 hunks)
  • packages/logger-plugin-std/src/helpers/helper-format-time.ts (1 hunks)
  • packages/logger-plugin-std/src/helpers/helper-merge-options.ts (1 hunks)
  • packages/logger-plugin-std/src/types/type-options.ts (1 hunks)
  • packages/logger-plugin-std/tests/std-plugin.spec.ts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • packages/logger-plugin-console/src/helpers/helper-format-time.ts
  • packages/logger-plugin-std/src/helpers/helper-merge-options.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • packages/logger-plugin-console/tests/console-plugin.spec.ts
  • packages/logger-plugin-std/src/types/type-options.ts
  • packages/logger-plugin-std/tests/std-plugin.spec.ts
  • packages/logger-plugin-std/src/create-std-plugin.ts
  • packages/logger-plugin-std/src/helpers/helper-format-time.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/logger-plugin-console/src/helpers/helper-assert-message.ts (1)
packages/logger/src/types/type-message.ts (1)
  • LoggerMessageObject (1-6)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: deploy (20.x)

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
README.md (2)

160-178: Missing fs import in the sample code

The snippet uses fs.appendFileSync but never imports fs, which will confuse copy-paste readers.

-import { definePlugin, LogLevel } from '@hyperse/logger';
+import { definePlugin, LogLevel } from '@hyperse/logger';
+import * as fs from 'node:fs';

116-120: Inconsistent phrasing of capability bullets

To stay polished and uniform:

- Support browser
+ Browser support

- Support node
+ Node.js support

Optional but improves readability.

Also applies to: 138-141

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 84a14f0 and 21b900d.

📒 Files selected for processing (4)
  • README.md (1 hunks)
  • packages/logger-plugin-console/src/create-console-plugin.ts (3 hunks)
  • packages/logger-plugin-console/src/helpers/index.ts (1 hunks)
  • packages/logger-plugin-std/src/helpers/index.ts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • packages/logger-plugin-std/src/helpers/index.ts
  • packages/logger-plugin-console/src/helpers/index.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/logger-plugin-console/src/create-console-plugin.ts
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
README.md

293-293: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (8)
packages/logger-plugin-stdout/tests/test-utils.ts (1)

1-5: Remove redundant await keyword.

The await keyword is unnecessary here since you're already returning a Promise directly.

-export async function sleep(ms = 1000) {
-  return await new Promise<void>((resolver) => {
+export async function sleep(ms = 1000) {
+  return new Promise<void>((resolver) => {
     setTimeout(resolver, ms);
   });
 }
packages/logger-plugin-stdout/LICENSE.md (2)

5-5: Add missing article for better grammar.

-This software is available under below licenses:
+This software is available under the below licenses:

14-14: Format email as proper markdown link.

-For more information about the Hyperse Commercial License (HCL) please contact hi@hyperse.net.
+For more information about the Hyperse Commercial License (HCL) please contact [hi@hyperse.net](mailto:hi@hyperse.net).
packages/logger-plugin-stdout/src/helpers/helper-assert-message.ts (1)

2-13: Consider simplifying object creation.

The explicit undefined assignments are unnecessary since name and stack are optional properties in LoggerMessageObject. However, the current explicit approach is also valid for clarity.

 export const assertMessage = (
   message: LoggerMessageObject | string
 ): LoggerMessageObject => {
   if (typeof message === 'string') {
     return {
       message: message,
-      name: undefined,
-      stack: undefined,
     };
   }
   return message;
 };
packages/logger-plugin-stdout/src/helpers/helper-format-message.ts (1)

12-146: Consider refactoring for better maintainability.

The formatMessage function is quite complex (~130 lines) and handles multiple responsibilities. Consider breaking it down into smaller, focused functions for better maintainability and testability.

Potential refactoring approach:

  • formatDateTime() - handles date/timestamp formatting
  • formatContext() - handles prefix, logger name, plugin name
  • formatContent() - handles message name, message, stack

This would make the code more modular and easier to test individual components.

packages/logger-plugin-stdout/tests/stdout-plugin.spec.ts (1)

29-29: Consider more robust async testing approach.

Using sleep() for timing in tests can be brittle and slow. Consider using more deterministic approaches like waiting for specific conditions or using fake timers if the plugin supports it.

Alternative approaches:

  • Mock the async parts of the plugin if possible
  • Use vi.waitFor() to wait for specific conditions
  • Consider making the plugin execution synchronous for testing
packages/logger-plugin-stdout/src/helpers/helper-format-time.ts (1)

33-105: Reduce code duplication in formatTime function.

The formatTime function has significant code duplication with repeated calls to addUnitOfTime. Consider using a loop or array-driven approach to reduce duplication.

+const TIME_UNIT_CONFIGS = [
+  { unit: TIME_UNITS.YEAR, name: 'y' },
+  { unit: TIME_UNITS.MONTH, name: 'm' },
+  { unit: TIME_UNITS.DAY, name: 'd' },
+  { unit: TIME_UNITS.HOUR, name: 'h' },
+  { unit: TIME_UNITS.MINUTE, name: 'min' },
+  { unit: TIME_UNITS.SECOND, name: 's' },
+  { unit: TIME_UNITS.MILLISECOND, name: 'ms' },
+] as const;

 export const formatTime = (
   time: Date,
   lastTime: Date,
   decorateColorFn: (s: string) => string,
   color: (s: string) => string,
   prefix: string
 ) => {
+  let remainingMs = time.getTime() - lastTime.getTime();
+  let formattedChangeInTime = ' ';
+  
+  for (const { unit, name } of TIME_UNIT_CONFIGS) {
+    const result = addUnitOfTime(prefix, remainingMs, decorateColorFn, unit, name);
+    formattedChangeInTime += result.formatted;
+    remainingMs = result.remaining;
+  }
+  
+  return color(formattedChangeInTime);
 };
packages/logger-plugin-stdout/README.md (1)

124-131: Specify language identifiers for fenced examples (markdownlint MD040)
All plain-text log output examples miss a language spec on the opening back-ticks, triggering MD040 and breaking some renderers’ syntax-highlight heuristics.

Add a lightweight identifier such as text (or console) to each block:

-```
+```text

Apply to every affected snippet in the ranges above.

Also applies to: 147-151, 159-163, 171-175, 177-181, 189-193, 298-302, 304-308, 310-314, 316-320, 322-328

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 21b900d and c0ef935.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (36)
  • .changeset/long-weeks-yawn.md (1 hunks)
  • README.md (1 hunks)
  • logger-mono.code-workspace (2 hunks)
  • packages/logger-plugin-stdout/.gitignore (1 hunks)
  • packages/logger-plugin-stdout/.vscode/launch.json (1 hunks)
  • packages/logger-plugin-stdout/.vscode/settings.json (1 hunks)
  • packages/logger-plugin-stdout/CHANGELOG.md (1 hunks)
  • packages/logger-plugin-stdout/LICENSE.md (1 hunks)
  • packages/logger-plugin-stdout/README.md (1 hunks)
  • packages/logger-plugin-stdout/eslint.config.js (1 hunks)
  • packages/logger-plugin-stdout/index.js (1 hunks)
  • packages/logger-plugin-stdout/lint-staged.config.mjs (1 hunks)
  • packages/logger-plugin-stdout/package.json (1 hunks)
  • packages/logger-plugin-stdout/src/constant.ts (1 hunks)
  • packages/logger-plugin-stdout/src/create-stdout-plugin.ts (1 hunks)
  • packages/logger-plugin-stdout/src/helpers/helper-assert-message.ts (1 hunks)
  • packages/logger-plugin-stdout/src/helpers/helper-color-applier.ts (1 hunks)
  • packages/logger-plugin-stdout/src/helpers/helper-format-message.ts (1 hunks)
  • packages/logger-plugin-stdout/src/helpers/helper-format-stack.ts (1 hunks)
  • packages/logger-plugin-stdout/src/helpers/helper-format-time.ts (1 hunks)
  • packages/logger-plugin-stdout/src/helpers/helper-is-loggable.ts (1 hunks)
  • packages/logger-plugin-stdout/src/helpers/helper-merge-options.ts (1 hunks)
  • packages/logger-plugin-stdout/src/helpers/helper-normalize-level.ts (1 hunks)
  • packages/logger-plugin-stdout/src/helpers/helper-str-pad.ts (1 hunks)
  • packages/logger-plugin-stdout/src/helpers/index.ts (1 hunks)
  • packages/logger-plugin-stdout/src/index.ts (1 hunks)
  • packages/logger-plugin-stdout/src/types/index.ts (1 hunks)
  • packages/logger-plugin-stdout/src/types/type-options.ts (1 hunks)
  • packages/logger-plugin-stdout/src/types/type-plugin.ts (1 hunks)
  • packages/logger-plugin-stdout/tests/stdout-plugin.spec.ts (1 hunks)
  • packages/logger-plugin-stdout/tests/stdout.ts (1 hunks)
  • packages/logger-plugin-stdout/tests/test-utils.ts (1 hunks)
  • packages/logger-plugin-stdout/tsconfig.build.json (1 hunks)
  • packages/logger-plugin-stdout/tsconfig.json (1 hunks)
  • packages/logger-plugin-stdout/tsup.config.ts (1 hunks)
  • packages/logger-plugin-stdout/vitest.config.ts (1 hunks)
✅ Files skipped from review due to trivial changes (22)
  • packages/logger-plugin-stdout/.vscode/settings.json
  • packages/logger-plugin-stdout/CHANGELOG.md
  • packages/logger-plugin-stdout/index.js
  • packages/logger-plugin-stdout/.gitignore
  • packages/logger-plugin-stdout/src/types/index.ts
  • packages/logger-plugin-stdout/src/index.ts
  • packages/logger-plugin-stdout/tsconfig.json
  • packages/logger-plugin-stdout/.vscode/launch.json
  • packages/logger-plugin-stdout/vitest.config.ts
  • packages/logger-plugin-stdout/tsconfig.build.json
  • packages/logger-plugin-stdout/eslint.config.js
  • packages/logger-plugin-stdout/src/helpers/helper-is-loggable.ts
  • packages/logger-plugin-stdout/tsup.config.ts
  • packages/logger-plugin-stdout/lint-staged.config.mjs
  • packages/logger-plugin-stdout/src/helpers/helper-merge-options.ts
  • packages/logger-plugin-stdout/src/constant.ts
  • packages/logger-plugin-stdout/src/helpers/index.ts
  • packages/logger-plugin-stdout/src/helpers/helper-normalize-level.ts
  • packages/logger-plugin-stdout/src/helpers/helper-color-applier.ts
  • packages/logger-plugin-stdout/package.json
  • packages/logger-plugin-stdout/src/types/type-plugin.ts
  • packages/logger-plugin-stdout/src/helpers/helper-str-pad.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • logger-mono.code-workspace
  • .changeset/long-weeks-yawn.md
  • README.md
🧰 Additional context used
🧬 Code Graph Analysis (4)
packages/logger-plugin-stdout/src/helpers/helper-format-stack.ts (1)
packages/logger-plugin-stdout/src/helpers/helper-color-applier.ts (1)
  • terminalColor (10-22)
packages/logger-plugin-stdout/src/types/type-options.ts (1)
packages/logger-plugin-stdout/src/types/type-color.ts (1)
  • Color (3-6)
packages/logger-plugin-stdout/src/helpers/helper-assert-message.ts (1)
packages/logger/src/types/type-message.ts (1)
  • LoggerMessageObject (1-6)
packages/logger-plugin-stdout/src/helpers/helper-format-message.ts (6)
packages/logger-plugin-stdout/src/types/type-plugin.ts (2)
  • StdoutPluginContext (4-4)
  • StdoutPluginMessage (6-6)
packages/logger-plugin-stdout/src/types/type-options.ts (1)
  • StdoutOptions (4-129)
packages/logger-plugin-stdout/src/helpers/helper-normalize-level.ts (1)
  • normalizeLevelData (6-18)
packages/logger-plugin-stdout/src/helpers/helper-color-applier.ts (2)
  • getColorApplier (24-37)
  • terminalColor (10-22)
packages/logger-plugin-stdout/src/helpers/helper-str-pad.ts (1)
  • strTimePad (47-49)
packages/logger-plugin-stdout/src/helpers/helper-format-stack.ts (1)
  • formatStack (15-18)
🪛 LanguageTool
packages/logger-plugin-stdout/LICENSE.md

[uncategorized] ~5-~5: You might be missing the article “the” here.
Context: ... Ltd) This software is available under below licenses: - Hyperse Commercial License...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

packages/logger-plugin-stdout/README.md

[uncategorized] ~219-~219: Loose punctuation mark.
Context: ... ``` Available Colors: - 'black', `'red'`, `'green'`, `'yellow'`, `'blue'...

(UNLIKELY_OPENING_PUNCTUATION)


[typographical] ~221-~221: Two consecutive commas
Context: ...t', 'magentaBright', 'cyanBright', 'whiteBright'-'bgBlack', 'bgRed', 'bgGreen', 'bgYellow', ...

(DOUBLE_PUNCTUATION)


[typographical] ~222-~222: Two consecutive commas
Context: ... 'bgBlue', 'bgMagenta', 'bgCyan', 'bgWhite' - 'bgBlackBright', 'bgRedBright', 'bgGreenBright', `'b...

(DOUBLE_PUNCTUATION)


[typographical] ~223-~223: Two consecutive commas
Context: ... 'bgMagentaBright', 'bgCyanBright', 'bgWhiteBright' - 'bold', 'dim', 'italic', 'underline', `'i...

(DOUBLE_PUNCTUATION)


[uncategorized] ~257-~257: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...ateStdoutPlugin()) .build(); ### Full Featured Configuration typescript const logg...

(EN_COMPOUND_ADJECTIVE_INTERNAL)


[uncategorized] ~337-~337: Possible missing comma found.
Context: ...lly detect if it's running in a Node.js environment and will exit gracefully with an error ...

(AI_HYDRA_LEO_MISSING_COMMA)

🪛 markdownlint-cli2 (0.17.2)
packages/logger-plugin-stdout/LICENSE.md

14-14: Bare URL used

(MD034, no-bare-urls)

packages/logger-plugin-stdout/README.md

124-124: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


147-147: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


159-159: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


171-171: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


177-177: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


189-189: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


298-298: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


304-304: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


310-310: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


316-316: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


322-322: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: deploy (20.x)
🔇 Additional comments (6)
packages/logger-plugin-stdout/src/helpers/helper-format-stack.ts (2)

3-13: LGTM! Good error handling in parseStack.

The function properly handles edge cases with null/undefined inputs and processes stack traces correctly.


15-18: Stack formatting looks good.

The formatting with indentation and red coloring provides good visual distinction for stack traces in console output.

packages/logger-plugin-stdout/src/types/type-options.ts (1)

1-129: Well-designed comprehensive options type.

The StdoutOptions type is well-structured with comprehensive JSDoc documentation, clear default values, and appropriate use of TypeScript features like mapped types for levelColor. The type covers all necessary configuration aspects for stdout logging.

packages/logger-plugin-stdout/src/helpers/helper-format-message.ts (1)

70-74: Fix the 12-hour clock conversion logic.

The timestamp conversion logic for 12-hour format has an issue. The condition use24HourClock || !(hours >= 13 || hours === 0) will not correctly convert 24-hour to 12-hour format.

-            `${strTimePad(
-              use24HourClock || !(hours >= 13 || hours === 0)
-                ? hours
-                : Math.abs(hours - 12)
-            )}:${strTimePad(time.getMinutes())}:${strTimePad(time.getSeconds())}`
+            `${strTimePad(
+              use24HourClock
+                ? hours
+                : hours === 0 ? 12 : hours > 12 ? hours - 12 : hours
+            )}:${strTimePad(time.getMinutes())}:${strTimePad(time.getSeconds())}`

Likely an incorrect or invalid review comment.

packages/logger-plugin-stdout/src/create-stdout-plugin.ts (1)

12-52: Clean and well-structured plugin implementation.

The plugin implementation follows good practices with:

  • Proper environment checks for Node.js
  • Clean separation of concerns using helper functions
  • Appropriate use of the pipeline pattern
  • Clear error handling with descriptive exit messages

The code is readable and maintainable.

packages/logger-plugin-stdout/README.md (1)

208-215: Add default colour mapping for Fatal log level
The earlier “Example” section shows a FATAL level, but the default levelColor table omits it, which may confuse users or imply the plugin ignores that level.

If LogLevel.Fatal exists in the core package, include it here:

   {
+    [LogLevel.Fatal]: ['red', 'bold'],
     [LogLevel.Error]: ['red'],
     [LogLevel.Warn]: ['yellow'],
     [LogLevel.Info]: ['green'],
     [LogLevel.Debug]: ['blue'],
     [LogLevel.Verbose]: ['magenta'],
   }

Otherwise, clarify in the README that Fatal is not supported.

Comment on lines +1 to +37
import { createLogger } from '@hyperse/logger';
import { LogLevel } from '@hyperse/logger';
import { createStdoutPlugin } from '../src/create-stdout-plugin.js';

const logger = createLogger({
name: 'hps-logger',
thresholdLevel: LogLevel.Verbose,
})
.use(createStdoutPlugin())
.build();

logger.info('info message');

logger.warn({
prefix: 'warn prefix',
name: 'warn name',
message: 'warn message',
});
logger.debug({
prefix: 'debug prefix',
name: 'debug name',
message: 'debug message',
});
logger.verbose({
prefix: 'verbose prefix',
name: 'verbose name',
message: 'verbose message',
});
try {
throw new Error('error message');
} catch (error: any) {
logger.error({
name: 'error name',
message: error.message,
stack: error.stack,
});
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider converting to proper unit tests or moving to examples.

This file demonstrates good usage of the logger and stdout plugin, but it's more of a manual test/demo than an automated unit test. Consider either:

  1. Moving this to an examples/ directory as a usage demonstration
  2. Converting to proper unit tests with assertions in a .spec.ts file

If keeping as a test, you could add assertions using the test utilities:

import { describe, it, expect } from 'vitest';
import { sleep } from './test-utils.js';

describe('Stdout Plugin', () => {
  it('should log messages without throwing', async () => {
    // Test setup
    const logger = createLogger({...}).use(createStdoutPlugin()).build();
    
    // Test execution
    expect(() => {
      logger.info('test message');
      logger.error({ message: 'error', stack: 'stack trace' });
    }).not.toThrow();
    
    await sleep(100); // Allow async processing
  });
});
🤖 Prompt for AI Agents
In packages/logger-plugin-stdout/tests/stdout.ts lines 1 to 37, the current code
acts as a manual test/demo without assertions. To fix this, either move the file
to an examples/ directory to serve as usage documentation or convert it into a
proper unit test by wrapping the logger calls inside a test framework structure
(e.g., using vitest's describe and it blocks) and add assertions to verify no
errors are thrown during logging. This will ensure automated verification and
better test coverage.

Comment on lines +6 to +7
// @ts-ignore
let mockStdLog: ReturnType<typeof vi.spyOn<typeof process.stdout, 'write'>>;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove @ts-ignore and improve type safety.

The @ts-ignore directive should be avoided. Consider using proper typing or @ts-expect-error with a specific comment explaining why the type assertion is necessary.

-  // @ts-ignore
-  let mockStdLog: ReturnType<typeof vi.spyOn<typeof process.stdout, 'write'>>;
+  let mockStdLog: ReturnType<typeof vi.spyOn>;

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In packages/logger-plugin-stdout/tests/stdout-plugin.spec.ts around lines 6 to
7, remove the @ts-ignore directive and improve type safety by explicitly typing
the mockStdLog variable. Use a proper type assertion or a more specific type
that matches the return type of vi.spyOn for process.stdout.write. If a type
error is unavoidable, replace @ts-ignore with @ts-expect-error and add a comment
explaining why the type assertion is necessary.

Comment on lines +22 to +31
let remainder = time.getTime() - lastTime.getTime();
const unitCount = Math.floor(remainder / unitValueInMilliseconds);

remainder = remainder % unitValueInMilliseconds;
return unitCount !== 0
? colorFn(prefix + unitCount + unitName) + ' '
: unitValueInMilliseconds === 1
? colorFn(prefix + '0') + ' '
: '';
};
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the remainder calculation logic.

The remainder calculation has a logical issue. The remainder is calculated but not properly used or propagated between time unit calculations, which could lead to incorrect time formatting.

-const addUnitOfTime = (
-  prefix: string,
-  time: Date,
-  lastTime: Date,
-  colorFn: (s: string) => string,
-  unitValueInMilliseconds: number,
-  unitName: string
-) => {
-  let remainder = time.getTime() - lastTime.getTime();
-  const unitCount = Math.floor(remainder / unitValueInMilliseconds);
-
-  remainder = remainder % unitValueInMilliseconds;
-  return unitCount !== 0
-    ? colorFn(prefix + unitCount + unitName) + ' '
-    : unitValueInMilliseconds === 1
-      ? colorFn(prefix + '0') + ' '
-      : '';
-};
+const addUnitOfTime = (
+  prefix: string,
+  remainingMs: number,
+  colorFn: (s: string) => string,
+  unitValueInMilliseconds: number,
+  unitName: string
+): { formatted: string; remaining: number } => {
+  const unitCount = Math.floor(remainingMs / unitValueInMilliseconds);
+  const remaining = remainingMs % unitValueInMilliseconds;
+  
+  const formatted = unitCount !== 0
+    ? colorFn(prefix + unitCount + unitName) + ' '
+    : unitValueInMilliseconds === 1
+      ? colorFn(prefix + '0') + ' '
+      : '';
+      
+  return { formatted, remaining };
+};

The formatTime function would then need to be updated to properly chain the remainder calculations.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In packages/logger-plugin-stdout/src/helpers/helper-format-time.ts around lines
22 to 31, the remainder calculation is done but not correctly propagated between
different time unit calculations, causing incorrect time formatting. Update the
logic so that the remainder from one unit calculation is passed and used in the
next unit calculation step, ensuring the time is correctly broken down into
units. Adjust the formatTime function accordingly to chain these remainder
values properly through each unit conversion.

@tianyingchun tianyingchun merged commit bf197e3 into hyperse-io:main Jul 2, 2025
3 checks passed
@github-actions github-actions bot mentioned this pull request Jul 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants