欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用go写一个docker(8)-介绍两个库cli和logrus

程序员文章站 2022-06-11 17:09:52
...

有了前面知识就可以开始写一个简单的docker了,但为了让这个docker好看一点,我们先了解一下会用到的两个库:cli 和 logrus

  1. github.com/urfave/cli

  2. github.com/sirupsen/logrus

关于go的版本

这里再啰嗦一下,go在1.12之后就正式支持go module了,通过go module管理使用第三方包非常的方便。如无特殊说明,这里用的go版本都是1.15的,使用go module来管理维护第三方库(和go path说再见吧)。

cli

我们写的docker是通过终端来交互使用的(不写界面奥),所以肯定要和命令行打交道。为了简化代码,我们会用到一个第三方命令行的库cli。

先安装一下:

1. 建一个cli的目录,初始化一下go mod

# mkdir cli
# cd cli
# go mod init cli

2.安装一下这个库

# go get github.com/urfave/cli
go: github.com/urfave/cli upgrade => v1.22.5

3.使用一下

示例代码:

package main
​
import (
  "fmt"
  "github.com/urfave/cli"
  "log"
  "os"
)
​
func main() {
  app := &cli.App{
    Name:    "hello",
    Usage:   "hello world example",
    Version: "1.10",
    Action: func(c *cli.Context) {
      for i := 0; i < c.NArg(); i++ {
        fmt.Printf("%d: %s\n", i+1, c.Args().Get(i))
      }
    },
  }
​
  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

build一下,运行看看

# go build cli.go
#  ./cli aa bb cc
1: aa
2: bb
3: cc
# ./cli --version
hello version 1.10
# ./cli -h
NAME:
   hello - hello world example
​
USAGE:
    [global options] command [command options] [arguments...]
​
VERSION:
   1.10
​
COMMANDS:
   help, h  Shows a list of commands or help for one command
​
GLOBAL OPTIONS:
   --help, -h     show help
   --version, -v  print the version

可以看到cli的使用和方便:初始化一个cli.App的结构体,并传入对应的参数即可,看看会用到的一些参数:

Name,Usage,Version:这几个是用在帮助中的。

Action:在调用cli后最终后执行的函数,传递的参数在cli.Context中获取。

Before:在执行命令前调用的函数(比如做些初始化的配置),传递的参数在cli.Context中获取。

type Command struct {
  // The name of the command
  Name string
  // short name of the command. Typically one character (deprecated, use `Aliases`)
  ShortName string
  // A list of aliases for the command
  Aliases []string
  // A short description of the usage of this command
  Usage string
  // Custom text to show on USAGE section of help
  UsageText string
  // A longer explanation of how the command works
  Description string
  // A short description of the arguments of this command
  ArgsUsage string
  // The category the command is part of
  Category string
  // The function to call when checking for bash command completions
  BashComplete BashCompleteFunc
  // An action to execute before any sub-subcommands are run, but after the context is ready
  // If a non-nil error is returned, no sub-subcommands are run
  Before BeforeFunc
  // An action to execute after any subcommands are run, but after the subcommand has finished
  // It is run even if Action() panics
  After AfterFunc
  // The function to call when this command is invoked
  Action interface{}
  // TODO: replace `Action: interface{}` with `Action: ActionFunc` once some kind
  // of deprecation period has passed, maybe?
​
  // Execute this function if a usage error occurs.
  OnUsageError OnUsageErrorFunc
  // List of child commands
  Subcommands Commands
  // List of flags to parse
  Flags []Flag
  // Treat all flags as normal arguments if true
  SkipFlagParsing bool
  // Skip argument reordering which attempts to move flags before arguments,
  // but only works if all flags appear after all arguments. This behavior was
  // removed n version 2 since it only works under specific conditions so we
  // backport here by exposing it as an option for compatibility.
  SkipArgReorder bool
  // Boolean to hide built-in help command
  HideHelp bool
  // Boolean to hide this command from help or completion
  Hidden bool
  // Boolean to enable short-option handling so user can combine several
  // single-character bool arguments into one
  // i.e. foobar -o -v -> foobar -ov
  UseShortOptionHandling bool
​
  // Full name of command for help, defaults to full command name, including parent commands.
  HelpName        string
  commandNamePath []string
​
  // CustomHelpTemplate the text template for the command help topic.
  // cli.go uses text/template to render templates. You can
  // render custom help text by setting this variable.
  CustomHelpTemplate string
}

logrus

相比于标准库log,logrus支持更多的日志级别:

var AllLevels = []Level{
  PanicLevel,
  FatalLevel,
  ErrorLevel,
  WarnLevel,
  InfoLevel,
  DebugLevel,
  TraceLevel,
}
​
// These are the different logging levels. You can set the logging level to log
// on your instance of logger, obtained with `logrus.New()`.
const (
  // PanicLevel level, highest level of severity. Logs and then calls panic with the
  // message passed to Debug, Info, ...
  PanicLevel Level = iota
  // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the
  // logging level is set to Panic.
  FatalLevel
  // ErrorLevel level. Logs. Used for errors that should definitely be noted.
  // Commonly used for hooks to send errors to an error tracking service.
  ErrorLevel
  // WarnLevel level. Non-critical entries that deserve eyes.
  WarnLevel
  // InfoLevel level. General operational entries about what's going on inside the
  // application.
  InfoLevel
  // DebugLevel level. Usually only enabled when debugging. Very verbose logging.
  DebugLevel
  // TraceLevel level. Designates finer-grained informational events than the Debug.
  TraceLevel
)

我们先安装一下:

# go get github.com/sirupsen/logrus
go: github.com/sirupsen/logrus upgrade => v1.7.0

使用比较方便,直接调用:

package main
​
import (
  log "github.com/sirupsen/logrus"
)
​
func main() {
  log.SetLevel(log.TraceLevel)
  log.SetFormatter(&log.JSONFormatter{})
​
  log.Trace("trace msg")
  log.Debug("debug msg")
  log.Info("info msg")
  log.Warn("warn msg")
  log.Error("error msg")
  log.Fatal("fatal msg")
  log.Panic("panic msg")
}

跑一下:

# go run log.go
{"level":"trace","msg":"trace msg","time":"2021-01-31T22:24:13+08:00"}
{"level":"debug","msg":"debug msg","time":"2021-01-31T22:24:13+08:00"}
{"level":"info","msg":"info msg","time":"2021-01-31T22:24:13+08:00"}
{"level":"warning","msg":"warn msg","time":"2021-01-31T22:24:13+08:00"}
{"level":"error","msg":"error msg","time":"2021-01-31T22:24:13+08:00"}
{"level":"fatal","msg":"fatal msg","time":"2021-01-31T22:24:13+08:00"}
exit status 1

logrus还支持很多自定义的配置,这里就不赘述了,感兴趣可以深入了解。
下期我们就开始写docker了。
谢谢阅读。
用go写一个docker(8)-介绍两个库cli和logrus