Skip to content
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.

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

perf(logger): cache ColorEnabled value #4006

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

markH5
Copy link

@markH5 markH5 commented Mar 17, 2025

Maybe no need to check it in loop ?
Just check one

Copy link

codecov bot commented Mar 17, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 91.32%. Comparing base (035c2d7) to head (8a81a74).

Additional details and impacted files
@@           Coverage Diff            @@
##             main    #4006    +/-   ##
========================================
  Coverage   91.32%   91.32%            
========================================
  Files         168      168            
  Lines       10687    10689     +2     
  Branches     3021     3174   +153     
========================================
+ Hits         9760     9762     +2     
  Misses        926      926            
  Partials        1        1            

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@@ -13,7 +13,8 @@ enum LogPrefix {
}

const humanize = (times: string[]) => {
const [delimiter, separator] = [',', '.']
Copy link
Member

Choose a reason for hiding this comment

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

These lines should not be changed.

Copy link
Author

Choose a reason for hiding this comment

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

this change doesn't align with the minor tweak mentioned in the title.
I believe modern JS engines will likely inline it after a few iterations anyway. That said, it still introduces unnecessary runtime overhead.

Copy link
Member

@usualoma usualoma Mar 18, 2025

Choose a reason for hiding this comment

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

It might be better to use a different PR, but I think it would be better to do the following because there is a lot of waste in the current humanize() and time().

/**
 * Humanize the time.
 * @param {number} time - The time to humanize.
 * @returns {string} The humanized time.
 * 
 * @example
 * ```ts
 * humanize(1000) // => 1,000
 * ```
 */
const humanize = (time: number): string =>
  time < 1000 ? String(time) : String(time).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,')

const time = (start: number): string => {
  const delta = Date.now() - start
  return delta < 1000 ? `${delta}ms` : `${humanize(Math.round(delta / 1000))}s`
}

Copy link
Member

Choose a reason for hiding this comment

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

Or rather, humanize() only does its job when the request is over 1000 seconds long, but since there are no such long requests normally, I feel that humanize() itself is unnecessary.

status: number = 0,
elapsed?: string
) {
const out =
prefix === LogPrefix.Incoming
? `${prefix} ${method} ${path}`
: `${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed}`
: `${prefix} ${method} ${path} ${colorStatus(status, colorEnabled)} ${elapsed}`
Copy link
Member

Choose a reason for hiding this comment

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

I like the following implementation. This is because the colorStatus argument can be left as one. I think it's better not to have the colorEnabled argument here.

diff --git a/src/middleware/logger/index.ts b/src/middleware/logger/index.ts
index 5bb45383..a358e4c5 100644
--- a/src/middleware/logger/index.ts
+++ b/src/middleware/logger/index.ts
@@ -26,18 +26,15 @@ const time = (start: number) => {
 }

 const colorStatus = (status: number) => {
-  const colorEnabled = getColorEnabled()
-  if (colorEnabled) {
-    switch ((status / 100) | 0) {
-      case 5: // red = error
-        return `\x1b[31m${status}\x1b[0m`
-      case 4: // yellow = warning
-        return `\x1b[33m${status}\x1b[0m`
-      case 3: // cyan = redirect
-        return `\x1b[36m${status}\x1b[0m`
-      case 2: // green = success
-        return `\x1b[32m${status}\x1b[0m`
-    }
+  switch ((status / 100) | 0) {
+    case 5: // red = error
+      return `\x1b[31m${status}\x1b[0m`
+    case 4: // yellow = warning
+      return `\x1b[33m${status}\x1b[0m`
+    case 3: // cyan = redirect
+      return `\x1b[36m${status}\x1b[0m`
+    case 2: // green = success
+      return `\x1b[32m${status}\x1b[0m`
   }
   // Fallback to unsupported status code.
   // E.g.) Bun and Deno supports new Response with 101, but Node.js does not.
@@ -52,13 +49,14 @@ function log(
   prefix: string,
   method: string,
   path: string,
+  colorEnabled: boolean,
   status: number = 0,
   elapsed?: string
 ) {
   const out =
     prefix === LogPrefix.Incoming
       ? `${prefix} ${method} ${path}`
-      : `${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed}`
+      : `${prefix} ${method} ${path} ${colorEnabled ? colorStatus(status) : status} ${elapsed}`
   fn(out)
 }

Copy link
Member

Choose a reason for hiding this comment

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

@usualoma, What do you think of this implementation?

Copy link
Member

Choose a reason for hiding this comment

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

${colorEnabled ? colorStatus(status) : status}

That's good, I was just thinking the same thing!

@yusukebe yusukebe changed the title chore:logger cache ColorEnabled value perf(logger): cache ColorEnabled value Mar 18, 2025
@yusukebe
Copy link
Member

Hi @markH5

Thank you for the PR. I think this is a good improvement. This will affect the performance issue, so I labeled this PR as perf.

@usualoma What do you think of this?

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.

3 participants