Skip to content

Conversation

@pujitm
Copy link
Member

@pujitm pujitm commented Aug 25, 2025

Resolve #1614

Summary by CodeRabbit

  • New Features

    • Start and Restart commands accept a validated --log-level option (now includes "fatal"); chosen level is applied to the running/restarted service and defaults to the LOG_LEVEL environment value when set.
  • Documentation

    • CLI docs updated to list the --log-level option and allowed levels (including fatal), show LOG_LEVEL as an environment-variable alternative, and include usage examples.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 25, 2025

Walkthrough

Adds a reusable --log-level CLI option (exported LogLevelOptions) used by Start and Restart commands; parses and validates the value, sets env.LOG_LEVEL (falling back to existing LOG_LEVEL) and passes it to PM2 with extendEnv: true so the started/restarted process receives the log level.

Changes

Cohort / File(s) Summary
CLI: Restart command
api/src/unraid-api/cli/restart.command.ts
- Exported LogLevelOptions (logLevel?: LogLevel).
- Added parseLogLevelOption function and parseLogLevel method decorated with @Option('--log-level <...>') (defaults to LOG_LEVEL).
- Updated run signature to async run(_?: string[], options: LogLevelOptions = {}).
- PM2 restart invoked with extendEnv: true and env: { LOG_LEVEL: options.logLevel }.
CLI: Start command
api/src/unraid-api/cli/start.command.ts
- run(_: string[], options: LogLevelOptions) now uses shared LogLevelOptions type.
- Imports LOG_LEVEL and parseLogLevelOption from restart command module.
- Builds const env = { LOG_LEVEL: options.logLevel } and calls PM2 start with extendEnv: true and raw: true/--update-env.
Docs: CLI reference
api/docs/public/cli.md
- Documented --log-level option (allowed values include fatal) for Start and Restart.
- Added Options subsection for Restart and examples showing LOG_LEVEL=trace usage.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant CLI as Start/Restart Command
  participant Parser as parseLogLevel
  participant PM2 as PM2
  participant App as Unraid Process

  User->>CLI: start|restart --log-level <level>
  CLI->>Parser: parseLogLevel(<level>) %%{bgColor:"#E8F6EF"}%%
  Parser-->>CLI: validated level
  CLI->>PM2: start/restart(..., { extendEnv: true, env: { LOG_LEVEL: levelOrDefault } }) %%{bgColor:"#FFF4E6"}%%
  PM2->>App: spawn process with LOG_LEVEL
  PM2-->>CLI: result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–30 minutes

Assessment against linked issues

Objective Addressed Explanation
Ensure --log-level CLI option changes the running service log level (#1614)
Accept environment alternative LOG_LEVEL and document usage (#1614)

Out-of-scope changes

(No out-of-scope functional changes detected related to the linked issue.)

Poem

A rabbit parsed the tiny flag,
Tuned the hum from soft to brag,
PM2 woke with carrot cheer,
Logs now whisper, loud and clear.
Hop — the restart's in the rear. 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/log-level-docs

🪧 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.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit 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:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@claude
Copy link

claude bot commented Aug 25, 2025

Claude finished @pujitm's task —— View job


Code Review Complete

Reviewing the diff/changeset for critical issues only:

  • Read changed files to understand modifications
  • Analyze added/modified lines for high-priority issues
  • Report findings focused on critical bugs, security, breaking changes, data loss risks

⚠️ CRITICAL ISSUE FOUND:

Line restart.command.ts:18 - The new parseLogLevelOption function throws an Error for invalid log levels, but this is called during CLI option parsing. If a user provides an invalid --log-level, this will cause an unhandled exception instead of graceful CLI validation. This could crash the CLI process unexpectedly.

Line start.command.ts:53 & restart.command.ts:65 - Both commands now call parseLogLevelOption(val) which can throw, but there's no try/catch handling around the option parsing in the CLI framework.

Recommendation: Either handle the exception in the option parser or use Commander.js built-in choices validation instead of throwing exceptions during option parsing.

Copy link
Contributor

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/src/unraid-api/cli/restart.command.ts (1)

26-30: Preserve environment and use the correct logLevel key

The current snippet clobbers the entire child‐process environment and reads from the wrong options property. Update as follows:

  • File: api/src/unraid-api/cli/restart.command.ts (around lines 26–30)
  • Replace options['log-level'] with the camelCase options.logLevel
  • Ensure the spawned PM2 process inherits your full environment by enabling Execa’s extendEnv (or by manually spreading process.env)

Suggested diff:

-                { tag: 'PM2 Restart', raw: true, env: { LOG_LEVEL: options['log-level'] } },
+                {
+                    tag: 'PM2 Restart',
+                    raw: true,
+                    extendEnv: true,
+                    env: { LOG_LEVEL: options.logLevel ?? 'info' }
+                },

This guarantees that all existing environment variables are preserved and that you’re referencing the correct option name.

🧹 Nitpick comments (3)
api/src/unraid-api/cli/restart.command.ts (3)

22-22: Make options optional to match nest-commander’s run signature

The second parameter is optional per the docs; marking it optional avoids potential runtime surprises if no options object is provided.

Apply this diff:

-    async run(_: string[], options: RestartCommandOptions): Promise<void> {
+    async run(_: string[], options?: RestartCommandOptions): Promise<void> {

24-25: Optional: include the log level in the status message

Helps with operability and debugging.

Apply this diff:

-            this.logger.info('Restarting the Unraid API...');
+            this.logger.info(`Restarting the Unraid API (log level: ${options?.logLevel ?? 'info'})...`);

50-57: Bind the option name explicitly and enforce valid values via Commander choices

  • Add name: 'logLevel' so the parsed option is exposed as options.logLevel.
  • Use choices: [...levels] to let Commander validate inputs and remove manual checks.

Apply this diff in api/src/unraid-api/cli/restart.command.ts (around lines 50–57):

     @Option({
-        flags: `--log-level <${levels.join('|')}>`,
+        flags: '-l, --log-level <level>',
         description: 'log level to use',
         defaultValue: 'info',
+        name: 'logLevel',
+        choices: [...levels],
     })
-    parseLogLevel(val: string): LogLevel {
-        return levels.includes(val as LogLevel) ? (val as LogLevel) : 'info';
-    }
+    parseLogLevel(val: string): LogLevel {
+        // Commander guarantees val ∈ levels
+        return val as LogLevel;
+    }

To verify locally, build and test the CLI:

#!/bin/bash
set -e

# 1) Build project
npm run build

# 2) Valid log-level should succeed
node dist/main.js restart --log-level debug --help >/dev/null

# 3) Invalid log-level should exit non-zero
if node dist/main.js restart --log-level verbose; then
  echo "❌ Invalid value was accepted"
  exit 1
else
  echo "✅ Invalid value correctly rejected"
fi

(Or, without building, run via ts-node:
npx ts-node api/src/unraid-api/cli/restart.command.ts restart --log-level debug --help)

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between b2e7801 and 3cd0d30.

📒 Files selected for processing (1)
  • api/src/unraid-api/cli/restart.command.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

TypeScript source files must use import specifiers with .js extensions for ESM compatibility

Files:

  • api/src/unraid-api/cli/restart.command.ts
api/src/unraid-api/**

📄 CodeRabbit inference engine (CLAUDE.md)

Place new API source files in api/src/unraid-api/ rather than legacy locations

Prefer adding new files to the Nest repo at api/src/unraid-api/ instead of legacy code

Files:

  • api/src/unraid-api/cli/restart.command.ts
**/*.{ts,tsx,js,jsx,vue}

📄 CodeRabbit inference engine (CLAUDE.md)

Avoid unnecessary or obvious comments; only add comments when needed for clarity

Files:

  • api/src/unraid-api/cli/restart.command.ts
🧬 Code graph analysis (1)
api/src/unraid-api/cli/restart.command.ts (1)
api/src/core/log.ts (2)
  • levels (6-6)
  • LogLevel (8-8)
🔇 Additional comments (1)
api/src/unraid-api/cli/restart.command.ts (1)

1-4: ESM import specifiers look correct

Internal imports use .js extensions and type-only import is used for LogLevel. No action needed.

js abuse 🥲
Copy link
Contributor

@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

♻️ Duplicate comments (1)
api/src/unraid-api/cli/restart.command.ts (1)

9-11: Fix option key: use logLevel?: LogLevel instead of 'log-level'?: string.

Commander maps --log-level to logLevel. Reading 'log-level' will be undefined at runtime and loses type safety.

Apply this diff:

 interface RestartCommandOptions {
-    'log-level'?: string;
+    logLevel?: LogLevel;
 }
🧹 Nitpick comments (1)
api/src/unraid-api/cli/restart.command.ts (1)

50-57: Option parsing is solid; add a short alias and tighten types (optional).

  • Add -l alias for ergonomics.
  • Current parser is fine; keeping both defaultValue: 'info' and the fallback in parseLogLevel is defensive. No change required, but you could rely on just one source of default to reduce duplication.

Apply this diff for the alias:

     @Option({
-        flags: `--log-level <${levels.join('|')}>`,
+        flags: `-l, --log-level <${levels.join('|')}>`,
         description: 'log level to use',
         defaultValue: 'info',
     })
     parseLogLevel(val: string): LogLevel {
         return levels.includes(val as LogLevel) ? (val as LogLevel) : 'info';
     }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3cd0d30 and ad20aef.

📒 Files selected for processing (1)
  • api/src/unraid-api/cli/restart.command.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

TypeScript source files must use import specifiers with .js extensions for ESM compatibility

Files:

  • api/src/unraid-api/cli/restart.command.ts
api/src/unraid-api/**

📄 CodeRabbit inference engine (CLAUDE.md)

Place new API source files in api/src/unraid-api/ rather than legacy locations

Prefer adding new files to the Nest repo at api/src/unraid-api/ instead of legacy code

Files:

  • api/src/unraid-api/cli/restart.command.ts
**/*.{ts,tsx,js,jsx,vue}

📄 CodeRabbit inference engine (CLAUDE.md)

Avoid unnecessary or obvious comments; only add comments when needed for clarity

Files:

  • api/src/unraid-api/cli/restart.command.ts
🧬 Code graph analysis (1)
api/src/unraid-api/cli/restart.command.ts (1)
api/src/core/log.ts (2)
  • levels (6-6)
  • LogLevel (8-8)
🔇 Additional comments (3)
api/src/unraid-api/cli/restart.command.ts (3)

1-1: ESM-compatible imports look good.

Third-party import is fine, and the rest of the file uses .js extensions for internal modules per our ESM guideline.


3-4: Good use of type-only import and .js specifier.

Importing LogLevel as a type and using .js on the alias path aligns with our ESM rules.


22-22: run signature matches nest-commander’s contract.

Accepts args?: string[] and options?: Record<string, unknown>; no issues spotted.

@pujitm pujitm marked this pull request as ready for review August 28, 2025 17:49
@pujitm pujitm requested a review from elibosley August 28, 2025 17:49
@pujitm pujitm changed the title fix: support --log-level fix(cli): support --log-level for start and restart cmds Aug 28, 2025
Copy link
Contributor

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/src/unraid-api/cli/start.command.ts (1)

46-50: Same issue: remove defaultValue: 'info' to allow env fallback.

Otherwise Start will always force info, ignoring LOG_LEVEL.

 @Option({
     flags: `--log-level <${levels.join('|')}>`,
-    description: 'log level to use',
-    defaultValue: 'info',
+    description: 'log level to use',
 })
♻️ Duplicate comments (1)
api/src/unraid-api/cli/restart.command.ts (1)

27-27: Great: extendEnv: true prevents clobbering the inherited env.

This addresses earlier feedback about preserving PATH and other vars.

🧹 Nitpick comments (5)
api/src/unraid-api/cli/restart.command.ts (1)

25-25: Precedence is right, but casing may vary across sources.

You’re mixing lowercase CLI values with uppercase LOG_LEVEL. Downstream normalizes via toUpperCase() (environment.ts), so behavior is correct. Optional: normalize here for clarity.

Possible tweak:

-const env = { LOG_LEVEL: options.logLevel ?? LOG_LEVEL };
+const env = { LOG_LEVEL: (options.logLevel ?? LOG_LEVEL) as string };

(or normalize explicitly to lower/upper consistently)

api/src/unraid-api/cli/start.command.ts (2)

4-4: Avoid type coupling between commands; move LogLevelOptions to a shared module.

Even as a type-only import, referencing another command is fragile. Consider exporting LogLevelOptions from @app/core/log.js (or @app/unraid-api/cli/types.js) and import from there.

Apply (example):

-import type { LogLevelOptions } from '@app/unraid-api/cli/restart.command.js';
+import type { LogLevelOptions } from '@app/core/log.js';

37-39: Use consistent log level for stdout messages.

Restart uses info; Start uses log. Prefer consistency.

-        if (stdout) {
-            this.logger.log(stdout.toString());
-        }
+        if (stdout) {
+            this.logger.info(stdout.toString());
+        }
api/docs/public/cli.md (2)

27-31: Clarify precedence with env vs flag.

Add a note that the flag overrides LOG_LEVEL when provided; otherwise the service uses LOG_LEVEL (or defaults per environment).

Proposed patch:

-Alternative: You can also set the log level using the `LOG_LEVEL` environment variable:
+Note: If `--log-level` is provided it takes precedence. Otherwise the service uses the `LOG_LEVEL` environment variable (falling back to its built-in default).
+
+You can set the log level using the `LOG_LEVEL` environment variable:

58-59: Mirror the precedence note in Restart section.

Maintain consistency with Start docs.

-Alternative: You can also set the log level using the `LOG_LEVEL` environment variable:
+Note: If `--log-level` is provided it takes precedence. Otherwise the service uses the `LOG_LEVEL` environment variable (falling back to its built-in default).
+
+You can set the log level using the `LOG_LEVEL` environment variable:
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 393d826 and eba3534.

📒 Files selected for processing (3)
  • api/docs/public/cli.md (2 hunks)
  • api/src/unraid-api/cli/restart.command.ts (3 hunks)
  • api/src/unraid-api/cli/start.command.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

TypeScript source files must use import specifiers with .js extensions for ESM compatibility

Files:

  • api/src/unraid-api/cli/start.command.ts
  • api/src/unraid-api/cli/restart.command.ts
api/src/unraid-api/**

📄 CodeRabbit inference engine (CLAUDE.md)

Place new API source files in api/src/unraid-api/ rather than legacy locations

Prefer adding new files to the Nest repo at api/src/unraid-api/ instead of legacy code

Files:

  • api/src/unraid-api/cli/start.command.ts
  • api/src/unraid-api/cli/restart.command.ts
**/*.{ts,tsx,js,jsx,vue}

📄 CodeRabbit inference engine (CLAUDE.md)

Avoid unnecessary or obvious comments; only add comments when needed for clarity

Files:

  • api/src/unraid-api/cli/start.command.ts
  • api/src/unraid-api/cli/restart.command.ts
🧬 Code graph analysis (2)
api/src/unraid-api/cli/start.command.ts (2)
api/src/unraid-api/cli/restart.command.ts (1)
  • LogLevelOptions (9-11)
api/src/environment.ts (1)
  • LOG_LEVEL (90-94)
api/src/unraid-api/cli/restart.command.ts (2)
api/src/environment.ts (1)
  • LOG_LEVEL (90-94)
api/src/core/log.ts (2)
  • levels (6-6)
  • LogLevel (8-8)
🔇 Additional comments (5)
api/src/unraid-api/cli/restart.command.ts (3)

3-5: ESM-ready imports look correct (.js extensions).

Good use of type-only import and .js extensions for ESM compatibility.


22-22: Run signature + default options: LGTM.

Accepting options = {} is safe and keeps the command backward-compatible.


56-58: Parser is fine; tighten return type via the option interface change.

Once LogLevelOptions.logLevel is typed to LogLevel, you can drop casts at call sites.

api/src/unraid-api/cli/start.command.ts (2)

27-33: Env precedence wiring is good; preserve inherited env.

Using options.logLevel ?? LOG_LEVEL and extendEnv: true mirrors Restart and avoids env loss.


51-53: Parser OK; align options typing to LogLevel.

After moving LogLevelOptions and typing logLevel?: LogLevel, this stays correct.

@elibosley
Copy link
Member

@pujitm the outstanding coderabbit suggestions seem smart but this is a great change to get in :)

Copy link
Contributor

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/src/unraid-api/cli/restart.command.ts (1)

22-31: Only set LOG_LEVEL when the flag is provided; otherwise rely on inherited env

Today we always pass a value for LOG_LEVEL, which can unintentionally override an existing, correct setting. Build env conditionally so pm2 --update-env inherits the caller’s LOG_LEVEL when the flag is omitted.

-            const env = { LOG_LEVEL: options.logLevel };
+            const env = options.logLevel ? { LOG_LEVEL: options.logLevel } : undefined;
             const { stderr, stdout } = await this.pm2.run(
-                { tag: 'PM2 Restart', raw: true, extendEnv: true, env },
+                { tag: 'PM2 Restart', raw: true, extendEnv: true, env },
                 'restart',
                 ECOSYSTEM_PATH,
                 '--update-env'
             );
♻️ Duplicate comments (1)
api/src/unraid-api/cli/restart.command.ts (1)

51-55: Remove defaultValue; it prevents true env fallback and may case-mismatch

With a default here, options.logLevel is always defined, so we never fall back to the existing environment. Also, LOG_LEVEL from environment is uppercase (e.g., INFO) while CLI levels are lowercase; the mismatch can lead to silent coercion later.

     @Option({
         flags: `--log-level <${levels.join('|')}>`,
         description: 'log level to use',
-        defaultValue: LOG_LEVEL,
     })
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between eba3534 and 9aec6e7.

📒 Files selected for processing (3)
  • api/docs/public/cli.md (2 hunks)
  • api/src/unraid-api/cli/restart.command.ts (3 hunks)
  • api/src/unraid-api/cli/start.command.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • api/docs/public/cli.md
  • api/src/unraid-api/cli/start.command.ts
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

TypeScript source files must use import specifiers with .js extensions for ESM compatibility

Files:

  • api/src/unraid-api/cli/restart.command.ts
api/src/unraid-api/**

📄 CodeRabbit inference engine (CLAUDE.md)

Place new API source files in api/src/unraid-api/ rather than legacy locations

Prefer adding new files to the Nest repo at api/src/unraid-api/ instead of legacy code

Files:

  • api/src/unraid-api/cli/restart.command.ts
**/*.{ts,tsx,js,jsx,vue}

📄 CodeRabbit inference engine (CLAUDE.md)

Avoid unnecessary or obvious comments; only add comments when needed for clarity

Files:

  • api/src/unraid-api/cli/restart.command.ts
🧬 Code graph analysis (1)
api/src/unraid-api/cli/restart.command.ts (2)
api/src/core/log.ts (2)
  • LogLevel (8-8)
  • levels (6-6)
api/src/environment.ts (1)
  • LOG_LEVEL (90-94)
🔇 Additional comments (2)
api/src/unraid-api/cli/restart.command.ts (2)

1-5: ESM imports look correct

Using .js specifiers and colocated module paths matches our ESM guideline.


9-11: Good: option type is precise

Typing logLevel as LogLevel prevents invalid strings at compile-time.

@github-actions
Copy link
Contributor

This plugin has been deployed to Cloudflare R2 and is available for testing.
Download it at this URL:

https://preview.dl.unraid.net/unraid-api/tag/PR1623/dynamix.unraid.net.plg

Copy link
Contributor

@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

♻️ Duplicate comments (1)
api/src/unraid-api/cli/restart.command.ts (1)

59-66: Remove the default to avoid overriding existing LOG_LEVEL; fail fast remains intact.

With a default, the option is always defined and you always inject a value, which prevents true fallback to an already-configured PM2/env value. This reiterates a prior comment, but it still applies with LOG_LEVEL.toLowerCase().

 @Option({
   flags: `--log-level <${levels.join('|')}>`,
   description: 'log level to use',
-  defaultValue: LOG_LEVEL.toLowerCase(),
 })
 parseLogLevel(val: string): LogLevel {
   return parseLogLevelOption(val);
 }

If you apply this, also remove the now-unused LOG_LEVEL import.

🧹 Nitpick comments (3)
api/src/unraid-api/cli/restart.command.ts (3)

3-5: ESM import specifiers look good; consider dropping LOG_LEVEL import if not used.

If you remove the default from the option (see comment below), LOG_LEVEL import becomes unnecessary here.


13-19: Trim the value before normalizing.

Handles accidental whitespace in flags or env, e.g., --log-level " debug ".

Apply:

-export function parseLogLevelOption(val: string, allowedLevels: string[] = [...levels]): LogLevel {
-    const normalized = val.toLowerCase() as LogLevel;
+export function parseLogLevelOption(val: string, allowedLevels: string[] = [...levels]): LogLevel {
+    const normalized = val.trim().toLowerCase() as LogLevel;
     if (allowedLevels.includes(normalized)) {
         return normalized;
     }
     throw new Error(`Invalid --log-level "${val}". Allowed: ${allowedLevels.join(', ')}`);
 }

30-36: Optional: log the effective level for observability.

Helps confirm which level PM2 received during troubleshooting.

-      const { stderr, stdout } = await this.pm2.run(
+      if (level) this.logger.info(`Using log level: ${level}`);
+      const { stderr, stdout } = await this.pm2.run(
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9aec6e7 and aad2b5b.

📒 Files selected for processing (2)
  • api/src/unraid-api/cli/restart.command.ts (3 hunks)
  • api/src/unraid-api/cli/start.command.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/src/unraid-api/cli/start.command.ts
🧰 Additional context used
📓 Path-based instructions (3)
api/src/unraid-api/**

📄 CodeRabbit inference engine (.cursor/rules/api-rules.mdc)

Prefer adding new files to the Nest repo at api/src/unraid-api/ instead of legacy code

Files:

  • api/src/unraid-api/cli/restart.command.ts
api/src/**

📄 CodeRabbit inference engine (CLAUDE.md)

Prefer adding new files to the NestJS code at api/src/unraid-api/ instead of legacy code

Files:

  • api/src/unraid-api/cli/restart.command.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

In TypeScript files, use .js extensions in import specifiers for ESM compatibility

Files:

  • api/src/unraid-api/cli/restart.command.ts
🧬 Code graph analysis (1)
api/src/unraid-api/cli/restart.command.ts (2)
api/src/core/log.ts (2)
  • LogLevel (8-8)
  • levels (6-6)
api/src/environment.ts (1)
  • LOG_LEVEL (90-94)
🔇 Additional comments (2)
api/src/unraid-api/cli/restart.command.ts (2)

9-11: Typed option shape is correct.

logLevel?: LogLevel aligns with Commander’s camelCase mapping and the allowed values.


30-36: No action: start matches restart’s env/log-level handling.

Comment on lines +30 to 36
async run(_?: string[], options: LogLevelOptions = {}): Promise<void> {
try {
this.logger.info('Restarting the Unraid API...');
const env = { LOG_LEVEL: options.logLevel };
const { stderr, stdout } = await this.pm2.run(
{ tag: 'PM2 Restart', raw: true },
{ tag: 'PM2 Restart', raw: true, extendEnv: true, env },
'restart',
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Don’t clobber existing PM2 env when flag is omitted; only set LOG_LEVEL when present.

Currently we always pass LOG_LEVEL, which can override the process’s saved/env-configured level. Respect “fallback to existing LOG_LEVEL” by conditionally setting it.

   async run(_?: string[], options: LogLevelOptions = {}): Promise<void> {
     try {
       this.logger.info('Restarting the Unraid API...');
-      const env = { LOG_LEVEL: options.logLevel };
+      // Use explicit flag if provided; else use shell env if set; else don't override PM2 env.
+      const level =
+        options.logLevel ??
+        (process.env.LOG_LEVEL ? parseLogLevelOption(process.env.LOG_LEVEL) : undefined);
+      const env: NodeJS.ProcessEnv | undefined = level ? { LOG_LEVEL: level } : undefined;
       const { stderr, stdout } = await this.pm2.run(
-        { tag: 'PM2 Restart', raw: true, extendEnv: true, env },
+        { tag: 'PM2 Restart', raw: true, extendEnv: true, ...(env ? { env } : {}) },
         'restart',
         ECOSYSTEM_PATH,
         '--update-env'
       );

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

🤖 Prompt for AI Agents
In api/src/unraid-api/cli/restart.command.ts around lines 30 to 36, the code
always passes a LOG_LEVEL key to PM2 which can overwrite a saved/previous
LOG_LEVEL; change the env construction to add LOG_LEVEL only when
options.logLevel is non-null/undefined (e.g., conditionally set env.LOG_LEVEL or
build env via a spread when options.logLevel is present) and only include the
env parameter in the pm2.run call when that env object is non-empty so existing
PM2 process env values are preserved when the flag is omitted.

@elibosley elibosley merged commit a1ee915 into main Aug 29, 2025
15 checks passed
@elibosley elibosley deleted the fix/log-level-docs branch August 29, 2025 14:56
elibosley pushed a commit that referenced this pull request Sep 2, 2025
🤖 I have created a release *beep* *boop*
---


## [4.18.0](v4.17.0...v4.18.0)
(2025-09-02)


### Features

* **api:** enhance OIDC redirect URI handling in service and tests
([#1618](#1618))
([4e945f5](4e945f5))


### Bug Fixes

* api key creation cli
([#1637](#1637))
([c147a6b](c147a6b))
* **cli:** support `--log-level` for `start` and `restart` cmds
([#1623](#1623))
([a1ee915](a1ee915))
* confusing server -&gt; status query
([#1635](#1635))
([9d42b36](9d42b36))
* use unraid css variables in sonner
([#1634](#1634))
([26a95af](26a95af))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
elibosley added a commit that referenced this pull request Sep 4, 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.

unraid-api --log-level not changing

3 participants