zapflag

package module
v0.0.0-...-f43cf22 Latest Latest
Warning

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

Go to latest
Published: May 28, 2021 License: Apache-2.0 Imports: 8 Imported by: 0

README

Package zapflag implements functions to use go.uber.org/zap with github.com/urfave/cli/v2

GoDoc

Example
package main

import (
	"os"

	"github.com/takumakei/go-exit"
	"github.com/takumakei/go-urfave-cli/clix"
	"github.com/takumakei/go-urfave-cli/zapflag"
	"github.com/urfave/cli/v2"
	"go.uber.org/zap"
)

func main() {
	zf := zapflag.New(clix.FlagPrefix("MINI_"))

	app := cli.NewApp()
	app.Flags = zf.Flags()
	app.Before = zf.InitGlobal
	app.After = func(c *cli.Context) error {
		zap.L().Sync()
		return nil
	}
	app.Action = func(c *cli.Context) error {
		zap.L().Info("hello world")
		return nil
	}
	exit.Exit(app.Run(os.Args))
}
outputs
$ mini --help
NAME:
   mini - A new cli application

USAGE:
   mini [global options] command [command options] [arguments...]

COMMANDS:
   help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --log-development, --ld                      enable development mode (default: false) [$MINI_LOG_DEVELOPMENT, $MINI_LD]
   --log-level level, --ll level                level [debug|info|warn|error|dpanic|panic|fatal] (default: auto) [$MINI_LOG_LEVEL, $MINI_LL]
   --log-with-caller, --lwc                     whether including caller (default: auto) [$MINI_LOG_WITH_CALLER, $MINI_LWC]
   --log-stack-trace, --lst                     whether including stack trace (default: auto) [$MINI_LOG_STACK_TRACE, $MINI_LST]
   --log-stack-trace-level level, --lstl level  level [debug|info|warn|error|dpanic|panic|fatal] (default: auto) [$MINI_LOG_STACK_TRACE_LEVEL, $MINI_LSTL]
   --log-date-format value, --ldf value         see https://pkg.go.dev/time#Time.Format (default: auto) [$MINI_LOG_DATE_FORMAT, $MINI_LDF]
   --log-field key=value, --lf key=value        key=value added to the logger [$MINI_LOG_FIELD, $MINI_LF]
   --log-path value, --lp value                 output path (default: auto) [$MINI_LOG_PATH, $MINI_LP]
   --log-err-path value, --lep value            error output path (default: auto) [$MINI_LOG_ERR_PATH, $MINI_LEP]
   --log-sampling-initial N, --lsi N            sampling initial count N (default: auto) [$MINI_LOG_SAMPLING_INITIAL, $MINI_LSI]
   --log-sampling-thereafter N, --lsth N        sampling thereafter count N (default: auto) [$MINI_LOG_SAMPLING_THEREAFTER, $MINI_LSTH]
   --help, -h                                   show help (default: false)
$ mini
{"level":"info","ts":1620542056.145781,"caller":"mini/main.go:24","msg":"hello world"}
$ mini --log-development
2021-05-09T15:34:21.037+0900    INFO    mini/main.go:24 hello world
$ mini --log-development --log-stack-trace-level info
2021-05-09T15:34:30.046+0900    INFO    mini/main.go:24 hello world
main.main.func2
        github.com/takumakei/go-urfave-cli/zapflag/examples/mini/main.go:24
github.com/urfave/cli/v2.(*App).RunContext
        github.com/urfave/cli/v2@v2.3.0/app.go:322
github.com/urfave/cli/v2.(*App).Run
        github.com/urfave/cli/v2@v2.3.0/app.go:224
main.main
        github.com/takumakei/go-urfave-cli/zapflag/examples/mini/main.go:27
runtime.main
        runtime/proc.go:225
$

Documentation

Overview

Package zapflag implements functions to use go.uber.org/zap with github.com/urfave/cli.

Example
zf := zapflag.New(clix.FlagPrefix("EXAMPLE_"))

app := cli.NewApp()
app.Name = "example"
app.HelpName = "example"
app.Flags = zf.Flags()
app.Before = zf.InitGlobal
app.After = func(c *cli.Context) error {
	_ = zap.L().Sync()
	return nil
}
app.Action = func(c *cli.Context) error {
	zap.L().Info("hello world")
	return nil
}
_ = app.Run([]string{"example", "--help"})
Output:

NAME:
   example - A new cli application

USAGE:
   example [global options] command [command options] [arguments...]

COMMANDS:
   help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --log-development, --ld                      enable development mode (default: false) [$EXAMPLE_LOG_DEVELOPMENT, $EXAMPLE_LD]
   --log-level level, --ll level                level [debug|info|warn|error|dpanic|panic|fatal] (default: auto) [$EXAMPLE_LOG_LEVEL, $EXAMPLE_LL]
   --log-with-caller, --lwc                     whether including caller (default: auto) [$EXAMPLE_LOG_WITH_CALLER, $EXAMPLE_LWC]
   --log-stack-trace, --lst                     whether including stack trace (default: auto) [$EXAMPLE_LOG_STACK_TRACE, $EXAMPLE_LST]
   --log-stack-trace-level level, --lstl level  level [debug|info|warn|error|dpanic|panic|fatal] (default: auto) [$EXAMPLE_LOG_STACK_TRACE_LEVEL, $EXAMPLE_LSTL]
   --log-date-format value, --ldf value         see https://pkg.go.dev/time#Time.Format (default: auto) [$EXAMPLE_LOG_DATE_FORMAT, $EXAMPLE_LDF]
   --log-field key=value, --lf key=value        key=value added to the logger [$EXAMPLE_LOG_FIELD, $EXAMPLE_LF]
   --log-path value, --lp value                 output path (default: auto) [$EXAMPLE_LOG_PATH, $EXAMPLE_LP]
   --log-err-path value, --lep value            error output path (default: auto) [$EXAMPLE_LOG_ERR_PATH, $EXAMPLE_LEP]
   --log-sampling-initial N, --lsi N            sampling initial count N (default: auto) [$EXAMPLE_LOG_SAMPLING_INITIAL, $EXAMPLE_LSI]
   --log-sampling-thereafter N, --lsth N        sampling thereafter count N (default: auto) [$EXAMPLE_LOG_SAMPLING_THEREAFTER, $EXAMPLE_LSTH]
   --help, -h                                   show help (default: false)

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func IgnoreError

func IgnoreError(error) error

IgnoreError returns always nil.

func Named

func Named(logger *zap.Logger, c *cli.Context) *zap.Logger

Named adds a new path segment of command/subcommand name to the logger's name.

Example
log := zap.NewExample()

app := cli.NewApp()
app.Name = "example"
app.Action = func(c *cli.Context) error { return nil }
app.Before = func(c *cli.Context) error {
	log := zapflag.Named(log, c)
	log.Info("named logger for root")
	return nil
}
app.Commands = []*cli.Command{
	{
		Name:   "hello",
		Action: func(c *cli.Context) error { return nil },
		Before: func(c *cli.Context) error {
			log := zapflag.Named(log, c)
			log.Info("named logger for hello")
			return nil
		},
		Subcommands: []*cli.Command{
			{
				Name:   "world",
				Action: func(c *cli.Context) error { return nil },
				Before: func(c *cli.Context) error {
					log := zapflag.Named(log, c)
					log.Info("named logger for world")
					return nil
				},
				Subcommands: []*cli.Command{
					{
						Name:   "melon",
						Action: func(c *cli.Context) error { return nil },
						Before: func(c *cli.Context) error {
							log := zapflag.Named(log, c)
							log.Info("named logger for melon")
							return nil
						},
					},
				},
			},
		},
	},
}
_ = app.Run([]string{"example", "hello", "world", "melon"})
Output:

{"level":"info","logger":"example","msg":"named logger for root"}
{"level":"info","logger":"example.hello","msg":"named logger for hello"}
{"level":"info","logger":"example.hello.world","msg":"named logger for world"}
{"level":"info","logger":"example.hello.world.melon","msg":"named logger for melon"}

func ParseZapFields

func ParseZapFields(ss []string) []zap.Field

ParseZapFields converts ss into []zap.Field. Each string of ss must have format 'key=value'. The key can contain '.'.

func Sync

func Sync(p **zap.Logger, fn ...ErrorFunc) func(*cli.Context) error

Sync calls Sync method of *zap.Logger of *p, returns its result. If fn is specified, the result is converted by them before returned.

This is intended to be used as cli.AfterFunc. see https://pkg.go.dev/github.com/urfave/cli/v2#AfterFunc

func SyncGlobal

func SyncGlobal(fn ...ErrorFunc) func(*cli.Context) error

SyncGlobal calls zap.L().Sync(), returns its result. If fn is specified, the result is converted by them before returned.

This is intended to be used as cli.AfterFunc. see https://pkg.go.dev/github.com/urfave/cli/v2#AfterFunc

func ZapFields

func ZapFields(v url.Values) []zap.Field

ZapFields converts v into []zap.Field.

For each key in v, if len(v[key]) is less than 2 the element is a result of zap.String. Otherwise the element is a result of zap.Strings.

func ZapTimeEncoder

func ZapTimeEncoder(v string) zapcore.TimeEncoder

ZapTimeEncoder converts v into zapcore.TimeEncoder.

If v is equal to "rfc3339nano" or "RFC3339Nano", it returns zapcore.RFC3339NanoTimeEncoder.
If v is equal to "rfc3339" or "RFC3339", it returns zapcore.RFC3339TimeEncoder.
If v is equal to "iso8601" or "ISO8601", it returns zapcore.ISO8601TimeEncoder.
If v is equal to "millis", it returns zapcore.EpochMillisTimeEncoder.
If v is equal to "nanos", it returns zapcore.EpochNanosTimeEncoder.
If v is equal to "unix", "epoch" or "", it returns zapcore.EpochTimeEncoder.
Otherwise it returns zapcore.TimeEncoderOfLayout(v).

Types

type ErrorFunc

type ErrorFunc func(err error) error

ErrorFunc converts err.

type Flags

type Flags struct {
	Name string

	FlagDevelopment  *cli.BoolFlag
	FlagLevel        *cli.GenericFlag
	FlagWithCaller   *cli.BoolFlag
	FlagStackTrace   *cli.BoolFlag
	FlagStackTraceLv *cli.GenericFlag
	FlagDateFormat   *cli.StringFlag
	FlagFields       *cli.StringSliceFlag
	FlagPaths        *cli.StringSliceFlag
	FlagErrPaths     *cli.StringSliceFlag

	FlagSamplingInitial    *cli.IntFlag
	FlagSamplingThereafter *cli.IntFlag

	FlagSet clix.FlagSet
}

Flags represents flags to build a zap.Logger.

func New

func New(prefix clix.FlagPrefix) *Flags

New returns NewName("", prefix).

func NewName

func NewName(name string, prefix clix.FlagPrefix) *Flags

NewName returns a *Flags.

func (*Flags) Config

func (f *Flags) Config() zap.Config

Config returns zap.Config initialized by f's values.

Following values affects the result.

f.Development()
f.LookupLevel()
f.LookupStackTrace()
f.LookupDateFormat()
f.LookupPaths()
f.LookupErrPaths()
f.SamplingConfig()

func (*Flags) DateFormat

func (f *Flags) DateFormat() string

DateFormat returns the value of f.FlagDateFormat.

func (*Flags) Development

func (f *Flags) Development() bool

Development returns the value of f.FlagDevelopment.

func (*Flags) ErrPaths

func (f *Flags) ErrPaths() []string

ErrPaths returns the value of f.FlagErrPaths.

func (*Flags) Fields

func (f *Flags) Fields() []string

Fields returns the value of f.FlagFields.

func (*Flags) Flags

func (f *Flags) Flags() []cli.Flag

Flags returns []cli.Flag.

Elements are following.

f.FlagDevelopment
f.FlagLevel
f.FlagWithCaller
f.FlagStackTrace
f.FlagStackTraceLv
f.FlagDateFormat
f.FlagFields
f.FlagPaths
f.FlagErrPaths
f.FlagSamplingInitial
f.FlagSamplingThereafter

func (*Flags) Init

func (f *Flags) Init(c *cli.Context) error

Init returns f.FlagSet.Init(c).

This is intended to be used as cli.BeforeFunc. see https://pkg.go.dev/github.com/urfave/cli/v2#BeforeFunc

func (*Flags) InitGlobal

func (f *Flags) InitGlobal(c *cli.Context) error

InitGlobal calls f.Init(c), then replaces the global logger with f.Logger().

This is intended to be used as cli.BeforeFunc. see https://pkg.go.dev/github.com/urfave/cli/v2#BeforeFunc

func (*Flags) InitVar

func (f *Flags) InitVar(p **zap.Logger) func(*cli.Context) error

InitVar returns the function that can be used as cli.BeforeFunc. The function calls f.Init and f.Logger to create a new logger. Finaly new logger is named with f.Name, saved into p.

func (*Flags) Level

func (f *Flags) Level() zapcore.Level

Level returns the value of f.FlagLevel.

func (*Flags) Logger

func (f *Flags) Logger() (*zap.Logger, error)

Logger calls f.RootLogger() and returns the logger named with f.Name if f.Name is not empty, otherwise returns the result of f.RootLogger().

func (*Flags) LookupDateFormat

func (f *Flags) LookupDateFormat() (string, bool)

LookupDateFormat returns the value of f.FlagDateFormat. If the flag is set by the environment variable or the command line argument the value is returned and the boolean is true. Otherwise the returned value is undefined and boolean will be false.

func (*Flags) LookupErrPaths

func (f *Flags) LookupErrPaths() ([]string, bool)

LookupErrPaths returns the value of f.FlagErrPaths. If the flag is set by the environment variable or the command line argument the value is returned and the boolean is true. Otherwise the returned value is undefined and boolean will be false.

func (*Flags) LookupFields

func (f *Flags) LookupFields() ([]string, bool)

LookupFields returns the value of f.FlagFields. If the flag is set by the environment variable or the command line argument the value is returned and the boolean is true. Otherwise the returned value is undefined and boolean will be false.

func (*Flags) LookupLevel

func (f *Flags) LookupLevel() (zapcore.Level, bool)

LookupLevel returns the value of f.FlagLevel. If the flag is set by the environment variable or the command line argument the value is returned and the boolean is true. Otherwise the returned value is undefined and boolean will be false.

func (*Flags) LookupPaths

func (f *Flags) LookupPaths() ([]string, bool)

LookupPaths returns the value of f.FlagPaths. If the flag is set by the environment variable or the command line argument the value is returned and the boolean is true. Otherwise the returned value is undefined and boolean will be false.

func (*Flags) LookupSamplingInitial

func (f *Flags) LookupSamplingInitial() (int, bool)

LookupSamplingInitial returns the value of f.FlagSamplingInitial. If the flag is set by the environment variable or the command line argument the value is returned and the boolean is true. Otherwise the returned value is undefined and boolean will be false.

func (*Flags) LookupSamplingThereafter

func (f *Flags) LookupSamplingThereafter() (int, bool)

LookupSamplingThereafter returns the value of f.SamplingThereafter. If the flag is set by the environment variable or the command line argument the value is returned and the boolean is true. Otherwise the returned value is undefined and boolean will be false.

func (*Flags) LookupStackTrace

func (f *Flags) LookupStackTrace() (bool, bool)

LookupStackTrace returns the value of f.FlagStackTrace. If the flag is set by the environment variable or the command line argument the value is returned and the boolean is true. Otherwise the returned value is undefined and boolean will be false.

func (*Flags) LookupStackTraceLv

func (f *Flags) LookupStackTraceLv() (zapcore.Level, bool)

LookupStackTraceLv returns the value of f.FlagStackTraceLv. If the flag is set by the environment variable or the command line argument the value is returned and the boolean is true. Otherwise the returned value is undefined and boolean will be false.

func (*Flags) LookupWithCaller

func (f *Flags) LookupWithCaller() (bool, bool)

LookupWithCaller returns the value of f.FlagWithCaller. If the flag is set by the environment variable or the command line argument the value is returned and the boolean is true. Otherwise the returned value is undefined and boolean will be false.

func (*Flags) Options

func (f *Flags) Options() []zap.Option

Options returns []zap.Option.

Following values affects the result.

  • f.LookupStackTraceLv()
  • f.LookupWithCaller()
  • f.LookupFields()

func (*Flags) Paths

func (f *Flags) Paths() []string

Paths returns the value of f.FlagPaths.

func (*Flags) RootLogger

func (f *Flags) RootLogger() (*zap.Logger, error)

RootLogger returns f.Config().Build(f.Options()...).

func (*Flags) SamplingConfig

func (f *Flags) SamplingConfig() *zap.SamplingConfig

SamplingConfig returns *zap.SamplingConfig. If at least one of f.FlagSamplingInitial or f.FlagSamplingThereafter is set, it returns non-nil value. Otherwise returns nil. The value that is not specified is same as the other value. The value of thereafter will not be less than 1.

func (*Flags) SamplingInitial

func (f *Flags) SamplingInitial() int

SamplingInitial returns the value of f.FlagSamplingInitial.

func (*Flags) SamplingThereafter

func (f *Flags) SamplingThereafter() int

SamplingThereafter returns the value of f.SamplingThereafter.

func (*Flags) StackTrace

func (f *Flags) StackTrace() bool

StackTrace returns the value of f.FlagStackTrace.

func (*Flags) StackTraceLv

func (f *Flags) StackTraceLv() zapcore.Level

StackTraceLv returns the value of f.FlagStackTraceLv.

func (*Flags) WithCaller

func (f *Flags) WithCaller() bool

WithCaller returns the value of f.FlagWithCaller.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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