cmd

package module
v2.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 17, 2024 License: MIT Imports: 25 Imported by: 12

README

Logo

Go Report Card Build Status Coverage Status Go Reference GitHub release GitHub license

Go cmd helper.

This provides helpers on top of github.com/urfave/cli.

Overview

Install with:

go get github.com/hamba/cmd/v2

Example

func yourAction(c *cli.Context) error {
    log, err := cmd.NewLogger(c)
	if err != nil {
		// Handle error.
	}

	stats, err := cmd.NewStatter(c, log)
	if err != nil {
		// Handle error.
	}

    tracer, err := cmd.NewTracer(c, log,
        semconv.ServiceNameKey.String("my-service"),
        semconv.ServiceVersionKey.String("1.0.0"),
    )
    if err != nil {
        // Handle error.
        return
    }
    defer tracer.Shutdown(context.Background())

    // Run your application here...
	
	return nil
}

Flags

Logger

The logger flags are used by cmd.NewLogger to create a hamba.Logger.

FlagLogFormat: --log.format, $LOG_FORMAT

This flag sets the log formatter to use. The available options are logfmt (default), json, console.

Example: --log.format=console

FlagLogLevel: --log.level, $LOG_LEVEL

This flag sets the log level to filer on. The available options are debug, info (default), warn, error, crit.

Example: --log.level=error

FlagLogCtx: --log.ctx, $LOG_CTX

This flag sets contextual key value pairs to set on all log messages. This flag can be specified multiple times.

Example: --log.ctx="app=my-app" --log.ctx="zone=eu-west"

Statter

The statter flags are used by cmd.NewStatter to create a new `hamba.Statter.

FlagStatsDSN: --stats.dsn, $STATS_DSN

This flag sets the DSN describing the stats reporter to use. The available options are statsd, prometheus, l2met, victoriametrics.

The DSN can in some situations specify the host and configuration values as shown in the below examples:

Statsd:

--stats.dsn="statsd://host:port?flushBytes=1432&flushInterval=10s"

The host and port are required. Optionally flushBytes and flushInterval can be set, controlling how often the stats will be sent to the Statsd server.

Prometheus:

--stats.dsn="prometheus://host:port"

or

--stats.dsn="prom://host:port"

The host and port are optional. If set they will start a prometheus http server on the specified host and port.

Victoria Metrics:

--stats.dsn="victoriametrics://host:port"

or

--stats.dsn="vm://host:port"

The host and port are optional. If set they will start a victoria metrics http server on the specified host and port.

l2met:

--stats.dsn="l2met://"

This report has no exposed options.

FlagStatsInterval: --stats.interval, $STATS_INTERVAL

This flag sets the interval at which the aggregated stats will be reported to the reporter.

Example: --stats-interval=10s

FlagStatsPrefix: --stats.prefix, $STATS_PREFIX

This flag sets the prefix attached to all stats keys.

Example: --stats.prefix=my-app.server

FlagStatsTags: --stats.tags, $STATS_TAGS

This flag sets tag key value pairs to set on all stats. This flag can be specified multiple times.

Example: --stats.tags="app=my-app" --stats.tags="zone=eu-west"

Profiler

The profiler flags are used by cmd.NewProfiler to create a Pyroscope *pyroscope.Profiler.

FlagProfilingDSN: --profiling.dsn, $PROFILING_DSN

This flag configures the URL, authentication and optionally the Tenant ID for Pyroscope.

Example: --profiling.dsn=https://user:pass@host/path?token=auth-token&tenantid=my-tenant-id

FlagProfileUploadRate: --profiling.upload-rate, $PROFILING_UPLOAD_RATE

This flag configures the rate at which profiles are uploaded.

Example: --profiling.upload-rate=10s

FlagProfilingTags: --profiling.tags, $PROFILING_TAGS

This configures a list of tags appended to every profile. This flag can be specified multiple times.

Example: --profiling.tags="app=my-app" --profiling.tags="zone=eu-west"

FlagProfilingTypes: --profiling.types, $PROFILING_TYPES

This configures the profile types that are captured. By default all supported types are captured. This flag can be specified multiple times.

Example: --profiling.types=cpu --profiling.types=inuse_object

Tracer

The tracing flags are used by cmd.NewTracer to create a new open telemetry trace.TraceProvider.

FlagTracingExporter: --tracing.exporter, $TRACING_EXPORTER

This flag sets the exporter to send spans to. The available options are zipkin, otlphttp and otlpgrpc.

Example: --tracing.exporter=otlphttp

FlagTracingEndpoint: --tracing.endpoint, $TRACING_ENDPOINT

This flag sets the endpoint the exporter should send traces to.

Example: --tracing.endpoint="agent-host:port" or --tracing.endpoint="http://host:port/api/v2"

FlagTracingEndpointInsecure: --tracing.endpoint-insecure, $TRACING_ENDPOINT_INSECURE

This flag sets the endpoint the exporter should send traces to.

Example: --tracing.endpoint-insecure

FlagTracingRatio: --tracing.ratio, $TRACING_RATIO

This flag sets the sample ratio of spans that will be reported to the exporter. This should be between 0 and 1.

Example: --tracing.ratio=0.2

FlagTracingTags: --tracing.tags, $TRACING_TAGS

This flag sets a list of tags appended to every trace. This flag can be specified multiple times.

Example: --tracing.tags="app=my-app" --tracing.tags="zone=eu-west"

Observer

The observe package exposes an Observer type which is essentially a helper that combines a logger, tracer and statter. It is useful if you use all three for your services and want to avoid carrying around many arguments.

Here is an example of how one might use it:

func yourAction(c *cli.Context) error {
     obsvr, err := observe.NewFromCLI(c, "my-service", &observe.Options{
        LogTimestamps: true,
        StatsRuntime:  true,
        TracingAttrs: []attribute.KeyValue{
            semconv.ServiceVersionKey.String("1.0.0"),
        },
    })
    if err != nil {
        return err
    }
    defer obsvr.Close()

	// Run your application here...

	return nil
}

It also exposes NewFake which allows you to pass fake loggers, tracers and statters in your tests easily.

Documentation

Overview

Package cmd implements cmd helpers.

This provides helpers on top of `github.com/urfave/cli`.

Example usage:

var c *cli.Context // Get this from your action

log, err := cmd.NewLogger(c)
if err != nil {
	// Handle error.
}

stats, err := cmd.NewStatter(c, log)
if err != nil {
	// Handle error.
}

Index

Examples

Constants

View Source
const (
	FlagLogFormat = "log.format"
	FlagLogLevel  = "log.level"
	FlagLogCtx    = "log.ctx"
)

Log flag constants declared for CLI use.

View Source
const (
	FlagProfilingDSN      = "profiling.dsn"
	FlagProfileUploadRate = "profiling.upload-rate"
	FlagProfilingTags     = "profiling.tags"
	FlagProfilingTypes    = "profiling.types"
)

Tracing flag constants declared for CLI use.

View Source
const (
	FlagStatsDSN      = "stats.dsn"
	FlagStatsInterval = "stats.interval"
	FlagStatsPrefix   = "stats.prefix"
	FlagStatsTags     = "stats.tags"
)

Stats flag constants declared for CLI use.

View Source
const (
	FlagTracingExporter         = "tracing.exporter"
	FlagTracingEndpoint         = "tracing.endpoint"
	FlagTracingEndpointInsecure = "tracing.endpoint-insecure"
	FlagTracingTags             = "tracing.tags"
	FlagTracingHeaders          = "tracing.headers"
	FlagTracingRatio            = "tracing.ratio"
)

Tracing flag constants declared for CLI use.

View Source
const CategoryLog = "Logging"

CategoryLog is the log flag category.

View Source
const CategoryProfiling = "Profiling"

CategoryProfiling is the profiling category.

View Source
const CategoryStats = "Stats"

CategoryStats is the stats flag category.

View Source
const CategoryTracing = "Tracing"

CategoryTracing is the tracing flag category.

Variables

View Source
var LogFlags = Flags{
	&cli.StringFlag{
		Name:     FlagLogFormat,
		Category: CategoryLog,
		Usage:    "Specify the format of logs. Supported formats: 'logfmt', 'json', 'console'.",
		EnvVars:  []string{"LOG_FORMAT"},
	},
	&cli.StringFlag{
		Name:     FlagLogLevel,
		Category: CategoryLog,
		Value:    "info",
		Usage:    "Specify the log level. e.g. 'trace', 'debug', 'info', 'error'.",
		EnvVars:  []string{"LOG_LEVEL"},
	},
	&cli.StringSliceFlag{
		Name:     FlagLogCtx,
		Category: CategoryLog,
		Usage:    "A list of context field appended to every log. Format: key=value.",
		EnvVars:  []string{"LOG_CTX"},
	},
}

LogFlags are flags that configure logging.

View Source
var MonitoringFlags = Flags{}.Merge(LogFlags, StatsFlags, ProfilingFlags, TracingFlags)

MonitoringFlags are flags that configure logging, stats, profiling and tracing.

View Source
var ProfilingFlags = Flags{
	&cli.StringFlag{
		Name:     FlagProfilingDSN,
		Category: CategoryProfiling,
		Usage: "The address to the Pyroscope server, in the format: " +
			"'http://basic:auth@server:port?token=auth-token&tenantid=tenant-id'.",
		EnvVars: []string{"PROFILING_DSN"},
	},
	&cli.DurationFlag{
		Name:     FlagProfileUploadRate,
		Category: CategoryProfiling,
		Usage:    "The rate at which profiles are uploaded.",
		Value:    15 * time.Second,
		EnvVars:  []string{"PROFILING_UPLOAD_RATE"},
	},
	&cli.StringSliceFlag{
		Name:     FlagProfilingTags,
		Category: CategoryProfiling,
		Usage:    "A list of tags appended to every profile. Format: key=value.",
		EnvVars:  []string{"PROFILING_TAGS"},
	},
	&cli.StringSliceFlag{
		Name:     FlagProfilingTypes,
		Category: CategoryProfiling,
		Usage:    "The type of profiles to include. Defaults to all.",
		EnvVars:  []string{"PROFILING_TYPES"},
	},
}

ProfilingFlags are flags that configure profiling.

View Source
var StatsFlags = Flags{
	&cli.StringFlag{
		Name:     FlagStatsDSN,
		Category: CategoryStats,
		Usage:    "The DSN of a stats backend.",
		EnvVars:  []string{"STATS_DSN"},
	},
	&cli.DurationFlag{
		Name:     FlagStatsInterval,
		Category: CategoryStats,
		Usage:    "The frequency at which the stats are reported.",
		Value:    time.Second,
		EnvVars:  []string{"STATS_INTERVAL"},
	},
	&cli.StringFlag{
		Name:     FlagStatsPrefix,
		Category: CategoryStats,
		Usage:    "The prefix of the measurements names.",
		EnvVars:  []string{"STATS_PREFIX"},
	},
	&cli.StringSliceFlag{
		Name:     FlagStatsTags,
		Category: CategoryStats,
		Usage:    "A list of tags appended to every measurement. Format: key=value.",
		EnvVars:  []string{"STATS_TAGS"},
	},
}

StatsFlags are flags that configure stats.

View Source
var TracingFlags = Flags{
	&cli.StringFlag{
		Name:     FlagTracingExporter,
		Category: CategoryTracing,
		Usage:    "The tracing backend. Supported: 'zipkin', 'otlphttp', 'otlpgrpc'.",
		EnvVars:  []string{"TRACING_EXPORTER"},
	},
	&cli.StringFlag{
		Name:     FlagTracingEndpoint,
		Category: CategoryTracing,
		Usage:    "The tracing backend endpoint.",
		EnvVars:  []string{"TRACING_ENDPOINT"},
	},
	&cli.BoolFlag{
		Name:     FlagTracingEndpointInsecure,
		Category: CategoryTracing,
		Usage:    "Determines if the endpoint is insecure.",
		EnvVars:  []string{"TRACING_ENDPOINT_INSECURE"},
	},
	&cli.StringSliceFlag{
		Name:     FlagTracingTags,
		Category: CategoryTracing,
		Usage:    "A list of tags appended to every trace. Format: key=value.",
		EnvVars:  []string{"TRACING_TAGS"},
	},
	&cli.StringSliceFlag{
		Name:     FlagTracingHeaders,
		Category: CategoryTracing,
		Usage:    "A list of headers appended to every trace when supported by the exporter. Format: key=value.",
		EnvVars:  []string{"TRACING_HEADERS"},
	},
	&cli.Float64Flag{
		Name:     FlagTracingRatio,
		Category: CategoryTracing,
		Usage:    "The ratio between 0 and 1 of sample traces to take.",
		Value:    0.5,
		EnvVars:  []string{"TRACING_RATIO"},
	},
}

TracingFlags are flags that configure tracing.

Functions

func NewLogger

func NewLogger(c *cli.Context) (*logger.Logger, error)

NewLogger returns a logger configured from the cli.

Example
var c *cli.Context // Get this from your action

log, err := cmd.NewLogger(c)
if err != nil {
	// Handle error.
	return
}

_ = log
Output:

func NewProfiler added in v2.10.0

func NewProfiler(c *cli.Context, svc string, log *logger.Logger) (*pyroscope.Profiler, error)

NewProfiler returns a profiler configured from the cli. If no profiler is configured, nil is returned.

Example
var c *cli.Context // Get this from your action

log, err := cmd.NewLogger(c)
if err != nil {
	// Handle error.
	return
}

prof, err := cmd.NewProfiler(c, "my-service", log)
if err != nil {
	// Handle error.
	return
}
if prof != nil {
	defer func() { _ = prof.Stop() }()
}

_ = prof
Output:

func NewStatter

func NewStatter(c *cli.Context, log *logger.Logger, opts ...statter.Option) (*statter.Statter, error)

NewStatter returns a statter configured from the cli.

Example
var c *cli.Context // Get this from your action

log, err := cmd.NewLogger(c)
if err != nil {
	// Handle error.
	return
}

stats, err := cmd.NewStatter(c, log)
if err != nil {
	// Handle error.
	return
}
defer stats.Close()

_ = stats
Output:

func NewTracer

func NewTracer(c *cli.Context, log *logger.Logger, resAttributes ...attribute.KeyValue) (*trace.TracerProvider, error)

NewTracer returns a tracer configured from the cli.

Example
var c *cli.Context // Get this from your action

log, err := cmd.NewLogger(c)
if err != nil {
	// Handle error.
	return
}

tracer, err := cmd.NewTracer(c, log,
	semconv.ServiceNameKey.String("my-service"),
	semconv.ServiceVersionKey.String("1.0.0"),
)
if err != nil {
	// Handle error.
	return
}
defer tracer.Shutdown(context.Background())

_ = tracer
Output:

func Split

func Split(slice []string, sep string) ([][2]string, error)

Split splits a slice of strings into an slice of arrays using the given separator.

Example
input := []string{"a=b", "foo=bar"} // Usually from a cli.StringSlice

tags, err := cmd.Split(input, "=")
if err != nil {
	// Handle error
}

fmt.Println(tags)
Output:

[[a b] [foo bar]]

Types

type Flags

type Flags []cli.Flag

Flags represents a set of CLI flags.

func (Flags) Merge

func (f Flags) Merge(flags ...Flags) Flags

Merge joins one or more Flags together, making a new set.

Directories

Path Synopsis
Package observe implements a type that combines statter, logger and tracer.
Package observe implements a type that combines statter, logger and tracer.
Package term implements a unified way to present output.
Package term implements a unified way to present output.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL