Skip to content

do not use global flags to configure klog#312

Open
rjeczalik wants to merge 1 commit into
deepgram:mainfrom
rjeczalik:rj/flag-klog
Open

do not use global flags to configure klog#312
rjeczalik wants to merge 1 commit into
deepgram:mainfrom
rjeczalik:rj/flag-klog

Conversation

@rjeczalik

@rjeczalik rjeczalik commented Aug 22, 2025

Copy link
Copy Markdown

Fixes #295.

Proposed changes

Given the example go prog:

package main

import (
	"flag"
	"fmt"

	"github.com/deepgram/deepgram-go-sdk/v3/pkg/client/listen"
	"github.com/deepgram/deepgram-go-sdk/v3/pkg/common"
)

var (
	myFlag = flag.String("myflag", "default", "A custom flag to test flag independence")
	debug  = flag.Bool("debug", false, "Enable debug mode")
)

func main() {
	common.Init(common.InitLib{
		LogLevel:      common.LogLevelFull,
		DebugFilePath: "/tmp/deepgram-debug.log",
	})

	client := listen.NewRESTWithDefaults()
	if client == nil {
		fmt.Println("Failed to create Deepgram client")
		return
	}

	flag.Parse()

	fmt.Printf("Custom flag value: %s\n", *myFlag)
	fmt.Printf("Debug mode: %t\n", *debug)
}

Calling common.Init overrides the prog flags:

$ go run prog.go
  -add_dir_header
    	If true, adds the file directory to the header of the log messages
  -alsologtostderr
    	log to standard error as well as files (no effect when -logtostderr=true)
  -debug
    	Enable debug mode
  -log_backtrace_at value
    	when logging hits line file:N, emit a stack trace
  -log_dir string
    	If non-empty, write log files in this directory (no effect when -logtostderr=true)
  -log_file string
    	If non-empty, use this log file (no effect when -logtostderr=true)
  -log_file_max_size uint
    	Defines the maximum size a log file can grow to (no effect when -logtostderr=true). Unit is megabytes. If the value is 0, the maximum file size is unlimited. (default 1800)
  -logtostderr
    	log to standard error instead of files (default true)
  -myflag string
    	A custom flag to test flag independence (default "default")
  -one_output
    	If true, only write logs to their native severity level (vs also writing to each lower severity level; no effect when -logtostderr=true)
  -skip_headers
    	If true, avoid header prefixes in the log messages
  -skip_log_headers
    	If true, avoid headers when opening log files (no effect when -logtostderr=true)
  -stderrthreshold value
    	logs at or above this threshold go to stderr when writing to files and stderr (no effect when -logtostderr=true or -alsologtostderr=true) (default 2)
  -v value
    	number for the log level verbosity
  -vmodule value
    	comma-separated list of pattern=N settings for file-filtered logging

This PR fixes the klog configuration to not touch global flags.

Types of changes

What types of changes does your code introduce to the community Go SDK?
Put an x in the boxes that apply

  • Bugfix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update or tests (if none of the other choices apply)

Checklist

Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code.

  • I have read the CONTRIBUTING doc
  • I have lint'ed all of my code using repo standards
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Further comments

Summary by CodeRabbit

  • Refactor

    • Isolated logging configuration to a dedicated flag set for more predictable, self-contained behavior. No public API changes.
  • Bug Fixes

    • Prevented unexpected changes to log verbosity caused by process command-line arguments.
    • Ensured debug file path settings reliably control log output destination and stderr behavior.
  • Chores

    • Improved initialization flow for logging to reduce side effects and conflicts with application flags.

@rjeczalik rjeczalik requested a review from lukeocodes as a code owner August 22, 2025 09:02
@coderabbitai

coderabbitai Bot commented Aug 22, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Replaces global flag parsing in pkg/common/init.go with a dedicated local FlagSet wired to klog. Sets verbosity and optional file logging via the FlagSet, and parses an empty argument list to ignore CLI args. Removes reliance on global flag.Parse while keeping Init signature unchanged.

Changes

Cohort / File(s) Summary
Logging flag handling refactor
pkg/common/init.go
Replace global flags with local flag.FlagSet; initialize klog with klog.InitFlags(fs); set v, logtostderr, log_file via fs.Set; parse with fs.Parse([]string{}) to ignore process args; preserve existing error handling; no public API changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor App
  participant Init as Init(init.InitLib)
  participant FS as flag.FlagSet (local)
  participant K as klog

  App->>Init: Init(initLib)
  Init->>FS: NewFlagSet("deepgram-go-sdk", ContinueOnError)
  Init->>K: InitFlags(FS)
  Init->>FS: Set("v", initLib.LogLevel)
  alt DebugFilePath provided
    Init->>FS: Set("logtostderr", "false")
    Init->>FS: Set("log_file", initLib.DebugFilePath)
  else No file path
    Init->>FS: Set("logtostderr", "true")
  end
  note over Init,FS: Parse empty args to avoid global CLI args
  Init->>FS: Parse([]string{})
  Init-->>App: return
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Assessment against linked issues

Objective Addressed Explanation
Prevent init() from breaking Go unit tests by removing global flag.Parse usage and ignoring test runner args (#295)

Assessment against linked issues: Out-of-scope changes

None found.

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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 @coderabbitai in a new review comment at the desired location with your query.
  • 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 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 @coderabbitai help to get the list of available commands.

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

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
pkg/common/init.go (3)

37-40: Nit: drop the redundant int64 cast in FormatInt.

LogLevel is already an int64 (see pkg/common/constants.go), so the extra cast is unnecessary.

- err := fs.Set("v", strconv.FormatInt(int64(init.LogLevel), 10))
+ err := fs.Set("v", strconv.FormatInt(init.LogLevel, 10))

42-51: Optional: pre-create the log directory and send error messages to stderr (with newline).

  • If DebugFilePath points to a directory that does not exist, initial writes will fail silently until first log. Pre-creating the directory provides earlier feedback.
  • Printing to stdout for errors in a library is surprising; prefer stderr and include a newline to avoid run-together messages.
 if init.DebugFilePath != "" {
-    err = fs.Set("logtostderr", "false")
+    err = fs.Set("logtostderr", "false")
     if err != nil {
-        fmt.Printf("Error setting logtostderr: %v", err)
+        fmt.Fprintf(os.Stderr, "deepgram-go-sdk: error setting logtostderr: %v\n", err)
     }
+    // Ensure the directory exists before klog attempts to open the file.
+    if mkErr := os.MkdirAll(filepath.Dir(init.DebugFilePath), 0o755); mkErr != nil {
+        fmt.Fprintf(os.Stderr, "deepgram-go-sdk: failed to create log directory for %q: %v\n", init.DebugFilePath, mkErr)
+    }
-    err = fs.Set("log_file", init.DebugFilePath)
+    err = fs.Set("log_file", init.DebugFilePath)
     if err != nil {
-        fmt.Printf("Error setting log_file: %v", err)
+        fmt.Fprintf(os.Stderr, "deepgram-go-sdk: error setting log_file: %v\n", err)
     }
 }

Additional changes required outside this hunk:

// add to imports
import (
    "os"
    "path/filepath"
)

53-53: Nit: add a clarifying comment about parsing an empty arg list.

A short comment helps future readers understand why CLI args are intentionally ignored here.

+    // Intentionally parse an empty argument list so we don't consume the program's flags.
     _ = fs.Parse([]string{})
📜 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 eb47266 and f9d4bfb.

📒 Files selected for processing (1)
  • pkg/common/init.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
pkg/common/init.go (1)
pkg/common/constants.go (1)
  • LogLevel (16-16)
🔇 Additional comments (2)
pkg/common/init.go (2)

33-36: Good fix: klog isolated to a private FlagSet (no global flag pollution).

Creating a dedicated FlagSet and wiring klog to it is the right approach to avoid clobbering program/go test flags. This directly addresses the linked issue without altering the public API.


33-53: No global flag parsing remains
Searches for flag.Parse, pflag.Parse, and any use of flag.CommandLine outside of pkg/common/init.go returned no matches. The only call to klog.InitFlags is in pkg/common/init.go (line 35), confirming that all flag setup is confined to the library’s own FlagSet.

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.

initializing the SDK in init() breaks go unit tests

1 participant