I'm reading this source code in the MicroMDM SCEP repository, https://github.com/micromdm/scep/blob/1e0c4b782f3f2e1e6f81da5f82444a6cedc89df3/cmd/scepclient/scepclient.go#L54-L65:
func run(cfg runCfg) error {
ctx := context.Background()
var logger log.Logger
{
if strings.ToLower(cfg.logfmt) == "json" {
logger = log.NewJSONLogger(os.Stderr)
} else {
logger = log.NewLogfmtLogger(os.Stderr)
}
stdlog.SetOutput(log.NewStdlibAdapter(logger))
logger = log.With(logger, "ts", log.DefaultTimestampUTC)
if !cfg.debug {
logger = level.NewFilter(logger, level.AllowInfo())
}
}
lginfo := level.Info(logger)
I wonder what the purpose is of the explicit block (the outer { ... }
)? Would this code not be exactly the same as if they were removed, like
func run(cfg runCfg) error {
ctx := context.Background()
var logger log.Logger
if strings.ToLower(cfg.logfmt) == "json" {
logger = log.NewJSONLogger(os.Stderr)
} else {
logger = log.NewLogfmtLogger(os.Stderr)
}
stdlog.SetOutput(log.NewStdlibAdapter(logger))
logger = log.With(logger, "ts", log.DefaultTimestampUTC)
if !cfg.debug {
logger = level.NewFilter(logger, level.AllowInfo())
}
lginfo := level.Info(logger)
Perhaps the explicit block is just to improve legibility?
In this case there seems to be no purpose to the extra block. No variables are declared inside the block. It doesn't add clarity, instead it's confusing you.
If clarity were desired you'd extract that code into a new function to initialize the logger.
func initLogger(cfg runCfg) log.Logger {
var logger log.Logger
if strings.ToLower(cfg.logfmt) == "json" {
logger = log.NewJSONLogger(os.Stderr)
} else {
logger = log.NewLogfmtLogger(os.Stderr)
}
stdlog.SetOutput(log.NewStdlibAdapter(logger))
logger = log.With(logger, "ts", log.DefaultTimestampUTC)
if !cfg.debug {
logger = level.NewFilter(logger, level.AllowInfo())
}
return logger
}
func run(cfg runCfg) error {
ctx := context.Background()
logger := initLogger(cfg)
lginfo := level.Info(logger)
...
My best guess is this block served some purpose in the past and whoever changed the code did not remove it, possibly also not sure if still served a purpose. Looking through the blame log of this function might give you an answer.