or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

assets.mdconfig.mdexpfmt.mdhelpers-templates.mdindex.mdmodel.mdpromslog-flag.mdpromslog.mdroute.mdserver.mdversion.md
tile.json

promslog-flag.mddocs/

Promslog/Flag Package

The promslog/flag package provides standardized flag interactions for promslog across Prometheus components using the Kingpin flag parsing library. This package should typically only be imported by main packages.

Import

import "github.com/prometheus/common/promslog/flag"

Overview

This package defines canonical flag names and helper functions for integrating promslog configuration with command-line flags. It uses the Kingpin library to provide consistent flag naming across all Prometheus components.

Constants

Flag Names

const LevelFlagName = "log.level"

Canonical flag name for the log level setting. This ensures consistency across all Prometheus components.

const FormatFlagName = "log.format"

Canonical flag name for the log format setting. This ensures consistency across all Prometheus components.

Variables

Help Text

var LevelFlagHelp string

Help text for the log.level flag. Contains description of the flag and valid options: "debug", "info", "warn", "error".

var FormatFlagHelp string

Help text for the log.format flag. Contains description of the flag and valid options: "logfmt", "json".

Functions

AddFlags

func AddFlags(a *kingpin.Application, config *promslog.Config)

Adds the standard logging flags to a Kingpin application and binds them to the provided Config struct.

Parameters:

  • a - The Kingpin application to add flags to
  • config - The promslog.Config struct that will be populated by flag values

Flags Added:

  • --log.level - Sets the log level (debug, info, warn, error)
  • --log.format - Sets the log format (logfmt, json)

Usage Examples

Basic Usage

package main

import (
    "os"

    "github.com/alecthomas/kingpin/v2"
    "github.com/prometheus/common/promslog"
    "github.com/prometheus/common/promslog/flag"
)

func main() {
    // Create Kingpin application
    app := kingpin.New("myapp", "My Prometheus component")

    // Create promslog config
    config := &promslog.Config{}

    // Add standard logging flags
    flag.AddFlags(app, config)

    // Parse flags
    kingpin.MustParse(app.Parse(os.Args[1:]))

    // Create logger from config
    logger := promslog.New(config)
    logger.Info("Application started")
}

With Additional Flags

package main

import (
    "os"

    "github.com/alecthomas/kingpin/v2"
    "github.com/prometheus/common/promslog"
    "github.com/prometheus/common/promslog/flag"
)

func main() {
    app := kingpin.New("server", "HTTP server with logging")

    // Application-specific flags
    var (
        listenAddr = app.Flag("listen-address", "Address to listen on").
            Default(":8080").String()
        metricsPath = app.Flag("metrics-path", "Path for metrics").
            Default("/metrics").String()
    )

    // Add standard logging flags
    config := &promslog.Config{}
    flag.AddFlags(app, config)

    // Parse all flags
    kingpin.MustParse(app.Parse(os.Args[1:]))

    // Use the configuration
    logger := promslog.New(config)
    logger.Info("Starting server",
        "address", *listenAddr,
        "metrics_path", *metricsPath)

    // ... rest of application
}

With Subcommands

package main

import (
    "os"

    "github.com/alecthomas/kingpin/v2"
    "github.com/prometheus/common/promslog"
    "github.com/prometheus/common/promslog/flag"
)

func main() {
    app := kingpin.New("tool", "Multi-command tool")

    // Global logging flags
    config := &promslog.Config{}
    flag.AddFlags(app, config)

    // Subcommand 1
    serve := app.Command("serve", "Start the server")
    serveAddr := serve.Flag("address", "Listen address").Default(":8080").String()

    // Subcommand 2
    check := app.Command("check", "Check configuration")
    checkFile := check.Flag("config", "Config file").Required().String()

    // Parse
    cmd := kingpin.MustParse(app.Parse(os.Args[1:]))

    // Create logger
    logger := promslog.New(config)

    // Execute subcommand
    switch cmd {
    case serve.FullCommand():
        logger.Info("Starting server", "address", *serveAddr)
        // ... serve logic
    case check.FullCommand():
        logger.Info("Checking config", "file", *checkFile)
        // ... check logic
    }
}

Custom Help Text

package main

import (
    "os"

    "github.com/alecthomas/kingpin/v2"
    "github.com/prometheus/common/promslog"
    promflag "github.com/prometheus/common/promslog/flag"
)

func main() {
    app := kingpin.New("myapp", "My application")
    app.HelpFlag.Short('h')

    config := &promslog.Config{}
    promflag.AddFlags(app, config)

    // The help text will automatically include:
    // --log.level=debug|info|warn|error  Only log messages with the given severity or above.
    // --log.format=logfmt|json           Output format of log messages.

    kingpin.MustParse(app.Parse(os.Args[1:]))

    logger := promslog.New(config)
    logger.Info("Started")
}

Integration with Version Flag

package main

import (
    "fmt"
    "os"

    "github.com/alecthomas/kingpin/v2"
    "github.com/prometheus/common/promslog"
    "github.com/prometheus/common/promslog/flag"
    "github.com/prometheus/common/version"
)

func main() {
    app := kingpin.New("myapp", "My Prometheus component")

    // Version flag
    app.Version(version.Print("myapp"))

    // Logging flags
    config := &promslog.Config{}
    flag.AddFlags(app, config)

    // Other flags...

    // Parse flags (--version will be handled automatically)
    kingpin.MustParse(app.Parse(os.Args[1:]))

    logger := promslog.New(config)
    logger.Info("Application started", "version", version.Version)
}

Testing Flag Parsing

package main

import (
    "bytes"
    "testing"

    "github.com/alecthomas/kingpin/v2"
    "github.com/prometheus/common/promslog"
    "github.com/prometheus/common/promslog/flag"
)

func TestLogFlags(t *testing.T) {
    tests := []struct {
        name     string
        args     []string
        wantLevel string
        wantFormat string
    }{
        {
            name:     "default values",
            args:     []string{},
            wantLevel: "info",
            wantFormat: "logfmt",
        },
        {
            name:     "debug json",
            args:     []string{"--log.level=debug", "--log.format=json"},
            wantLevel: "debug",
            wantFormat: "json",
        },
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            app := kingpin.New("test", "Test app")
            config := &promslog.Config{}
            flag.AddFlags(app, config)

            _, err := app.Parse(tt.args)
            if err != nil {
                t.Fatalf("Parse failed: %v", err)
            }

            logger := promslog.New(config)
            if config.Level.String() != tt.wantLevel {
                t.Errorf("Level = %v, want %v", config.Level.String(), tt.wantLevel)
            }
            if config.Format.String() != tt.wantFormat {
                t.Errorf("Format = %v, want %v", config.Format.String(), tt.wantFormat)
            }

            // Verify logger works
            var buf bytes.Buffer
            config.Writer = &buf
            logger = promslog.New(config)
            logger.Info("test message")

            if buf.Len() == 0 {
                t.Error("Logger produced no output")
            }
        })
    }
}

Command-Line Examples

Display Help

./myapp --help

Output will include:

usage: myapp [<flags>]

Flags:
  -h, --help                     Show context-sensitive help
      --log.level=info           Only log messages with the given severity or above. One of: [debug, info, warn, error]
      --log.format=logfmt        Output format of log messages. One of: [logfmt, json]

Set Log Level

# Debug level (most verbose)
./myapp --log.level=debug

# Info level (default)
./myapp --log.level=info

# Warn level (warnings and errors only)
./myapp --log.level=warn

# Error level (errors only)
./myapp --log.level=error

Set Log Format

# Logfmt format (default)
./myapp --log.format=logfmt

# JSON format
./myapp --log.format=json

Combined Usage

# Debug level with JSON format
./myapp --log.level=debug --log.format=json

# Short form (if defined)
./myapp --log.level=debug --log.format=json --listen-address=:9090

Notes

Standard Flag Names

Always use the constants LevelFlagName and FormatFlagName when referencing these flags in code to ensure consistency:

// Good
fmt.Println("Use", flag.LevelFlagName, "to set log level")

// Avoid hardcoding
fmt.Println("Use --log.level to set log level")

Kingpin Dependency

This package requires github.com/alecthomas/kingpin/v2. If you're using a different flag parsing library, use the promslog package directly and implement your own flag bindings.

Config Initialization

The Config struct passed to AddFlags will be populated with Level and Format fields. You can still set other Config fields (Style, Writer) manually:

config := &promslog.Config{
    Style:  promslog.GoKitStyle,
    Writer: customWriter,
}
flag.AddFlags(app, config)

Flag Defaults

The default values are:

  • Level: info
  • Format: logfmt

These defaults are set by the promslog package itself, not by the flag package.