simplify logging

This commit is contained in:
Greg T. Wallace 2024-02-03 11:38:31 -05:00
parent 2c4e3df0a5
commit 201aedce1c
8 changed files with 36 additions and 93 deletions

View file

@ -3,11 +3,12 @@ package app
import (
"context"
"errors"
"io"
"log"
"os"
"github.com/peterbourgon/ff/v4"
"github.com/peterbourgon/ff/v4/ffhelp"
"go.uber.org/zap"
)
const (
@ -16,21 +17,24 @@ const (
// struct for receivers to use common app pieces
type app struct {
logger *zap.SugaredLogger
cmd *ff.Command
config *config
stdLogger *log.Logger
debugLogger *log.Logger
errLogger *log.Logger
cmd *ff.Command
config *config
}
// actual application start
func Start(args []string) {
// make app w/ initial logger pre-config
initLogLevel := "debug"
// make app w/ logger
app := &app{
logger: makeZapLogger(&initLogLevel),
stdLogger: log.New(os.Stdout, "", 0),
debugLogger: log.New(io.Discard, "", 0), // discard debug logging by default
errLogger: log.New(os.Stderr, "", 0),
}
// log start
app.logger.Infof("apc-p15-tool v%s", appVersion)
app.stdLogger.Printf("apc-p15-tool v%s", appVersion)
// get os.Args if args unspecified in func
if args == nil {
@ -40,8 +44,8 @@ func Start(args []string) {
// get & parse config
err := app.getConfig(args)
// re-init logger with configured log level
app.logger = makeZapLogger(app.config.logLevel)
// if debug logging, make real debug logger
app.debugLogger = log.New(os.Stdout, "debug: ", 0)
// deal with config err (after logger re-init)
if err != nil {
@ -49,7 +53,7 @@ func Start(args []string) {
if errors.Is(err, ff.ErrHelp) {
// help explicitly requested
app.logger.Info("\n\n", ffhelp.Command(app.cmd))
app.stdLogger.Printf("\n%s\n", ffhelp.Command(app.cmd))
} else if errors.Is(err, ff.ErrDuplicateFlag) ||
errors.Is(err, ff.ErrUnknownFlag) ||
@ -57,13 +61,13 @@ func Start(args []string) {
errors.Is(err, ErrExtraArgs) {
// other error that suggests user needs to see help
exitCode = 1
app.logger.Error(err)
app.logger.Info("\n\n", ffhelp.Command(app.cmd))
app.errLogger.Print(err)
app.stdLogger.Printf("\n%s\n", ffhelp.Command(app.cmd))
} else {
// any other error
exitCode = 1
app.logger.Error(err)
app.errLogger.Print(err)
}
os.Exit(exitCode)
@ -74,9 +78,14 @@ func Start(args []string) {
err = app.cmd.Run(context.Background())
if err != nil {
exitCode = 1
app.logger.Error(err)
app.errLogger.Print(err)
// if extra args, show help
if errors.Is(err, ErrExtraArgs) {
app.stdLogger.Printf("\n%s\n", ffhelp.Command(app.cmd))
}
}
app.logger.Info("apc-p15-tool done")
app.stdLogger.Print("apc-p15-tool done")
os.Exit(exitCode)
}

View file

@ -41,7 +41,7 @@ func (app *app) cmdCreate(_ context.Context, args []string) error {
return fmt.Errorf("create: failed to write apc p15 file (%s)", err)
}
app.logger.Infof("create: apc p15 file %s written to disk", fileName)
app.stdLogger.Printf("create: apc p15 file %s written to disk", fileName)
return nil
}

View file

@ -67,8 +67,8 @@ func (app *app) cmdInstall(cmdCtx context.Context, args []string) error {
// log fingerprint for debugging
actualHashB64 := base64.RawStdEncoding.EncodeToString(actualHash)
actualHashHex := hex.EncodeToString(actualHash)
app.logger.Debugf("ssh: remote server key fingerprint (b64): %s", actualHashB64)
app.logger.Debugf("ssh: remote server key fingerprint (hex): %s", actualHashHex)
app.debugLogger.Printf("ssh: remote server key fingerprint (b64): %s", actualHashB64)
app.debugLogger.Printf("ssh: remote server key fingerprint (hex): %s", actualHashHex)
// allow base64 format
if actualHashB64 == *app.config.install.fingerprint {
@ -120,7 +120,7 @@ func (app *app) cmdInstall(cmdCtx context.Context, args []string) error {
}
// done
app.logger.Infof("install: apc p15 file installed on %s", *app.config.install.hostAndPort)
app.stdLogger.Printf("install: apc p15 file installed on %s", *app.config.install.hostAndPort)
return nil
}

View file

@ -25,8 +25,8 @@ type keyCertPemCfg struct {
// app's config options from user
type config struct {
logLevel *string
create struct {
debugLogging *bool
create struct {
keyCertPemCfg
outFilePath *string
}
@ -54,8 +54,7 @@ func (app *app) getConfig(args []string) error {
// apc-p15-tool -- root command
rootFlags := ff.NewFlagSet("apc-p15-tool")
cfg.logLevel = rootFlags.StringEnum('l', "loglevel", "log level: debug, info, warn, error, dpanic, panic, or fatal",
"info", "debug", "warn", "error", "dpanic", "panic", "fatal")
cfg.debugLogging = rootFlags.BoolLong("debug", "set this flag to enable additional debug logging messages")
rootCmd := &ff.Command{
Name: "apc-p15-tool",

View file

@ -1,47 +0,0 @@
package app
import (
"os"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// makeZapLogger creates a logger for the app; if log level is nil or does not parse
// the default 'Info' level will be used.
func makeZapLogger(logLevel *string) *zap.SugaredLogger {
// default info level
zapLevel := zapcore.InfoLevel
var parseErr error
// try to parse specified level (if there is one)
if logLevel != nil {
parseLevel, err := zapcore.ParseLevel(*logLevel)
if err != nil {
parseErr = err
} else {
zapLevel = parseLevel
}
}
// make zap config
config := zap.NewProductionEncoderConfig()
config.EncodeTime = zapcore.ISO8601TimeEncoder
config.LineEnding = "\n"
// no stack trace
config.StacktraceKey = ""
// make logger
consoleEncoder := zapcore.NewConsoleEncoder(config)
core := zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), zapLevel)
logger := zap.New(core, zap.AddCaller(), zap.AddStacktrace(zapcore.ErrorLevel)).Sugar()
// log deferred parse error if there was one
if logLevel != nil && parseErr != nil {
logger.Errorf("failed to parse requested log level \"%s\" (%s)", *logLevel, parseErr)
}
return logger
}

View file

@ -7,7 +7,7 @@ import (
// pemToAPCP15 reads the specified pem files and returns the apc p15 bytes
func (app *app) pemToAPCP15(keyPem, certPem []byte, parentCmdName string) ([]byte, error) {
app.logger.Infof("%s: making apc p15 file from pem", parentCmdName)
app.stdLogger.Printf("%s: making apc p15 file from pem", parentCmdName)
// make p15 struct
p15, err := pkcs15.ParsePEMToPKCS15(keyPem, certPem)
@ -15,7 +15,7 @@ func (app *app) pemToAPCP15(keyPem, certPem []byte, parentCmdName string) ([]byt
return nil, fmt.Errorf("%s: failed to parse pem files (%w)", parentCmdName, err)
}
app.logger.Infof("%s: successfully loaded pem files", parentCmdName)
app.stdLogger.Printf("%s: successfully loaded pem files", parentCmdName)
// make file bytes
p15File, err := p15.ToP15File()
@ -32,7 +32,7 @@ func (app *app) pemToAPCP15(keyPem, certPem []byte, parentCmdName string) ([]byt
// combine header with file
apcFile := append(apcHeader, p15File...)
app.logger.Infof("%s: apc p15 file data succesfully generated", parentCmdName)
app.stdLogger.Printf("%s: apc p15 file data succesfully generated", parentCmdName)
return apcFile, nil
}