Skip to content

Instantly share code, notes, and snippets.

@sheldonhull
Last active August 15, 2022 18:41
Show Gist options
  • Save sheldonhull/8f7e631493213b4f07ce824d0df70907 to your computer and use it in GitHub Desktop.
Save sheldonhull/8f7e631493213b4f07ce824d0df70907 to your computer and use it in GitHub Desktop.
Simple Log for Leetcode, Hackerank, and other tools using standard library. This is to simplify the need to comment out a bunch of fmt statements and instead provide a lighweight boilerplate for simple log output with indentation that can be disabled when ready with changing level in stuct.
// requires go 1.18
import (
"os"
"fmt"
)
func info(format string, a ...any) (n int, err error) {
return fmt.Fprintf(os.Stdout, format + "\n", a...)
}
package main
import (
"fmt"
"strings"
)
// LOGGER
// Simplified Logging for Leetcode/Hackerrank/Algoexport
// Uses std library
// Set the LogLevel to disable without having to comment and uncomment
// Or bump up to debug level to show full output in detail.
//
// Got tired of not having access to zerolog and other level based loggers, so this is to save the boilerplate.
//
// sheldonhull
const logLevel = 2
type log struct {
// Level is a simple int of disabled=0, info=1, debug=2
Level int
// Indent is set to 0, but setting to a new value will indent output of logging for easier debugging
Indent int
}
// Indent just indents the code by `n` tabs to allow for easier review of nested logic.
func (l *log) IndentPrefix(indentLevel int) string {
return strings.Repeat("\t", indentLevel)
}
// Info takes indent level, string with formatting directories and args.
func (l *log) Infof(idt int, msg string, args ...interface{}) {
if l.Level > 0 {
fmt.Printf("[info] "+l.IndentPrefix(idt)+" "+msg+"\n", args...)
}
}
// Debug takes indent level, string with formatting directories and args.
func (l *log) Debugf(idt int, msg string, args ...interface{}) {
if l.Level == 2 {
fmt.Printf("[debug]"+l.IndentPrefix(idt)+" "+msg+"\n", args...)
}
}
// END LOGGER
func main() {
slog := &log{Level: logLevel}
fmt.Println("current log level", slog.LogLevel())
slog.Infof(0, "starting loop")
slog.Infof(1, "starting loop: %s", "foobar")
slog.Debugf(1, "starting loop: %s", "foobar")
slog.Infof(2, "nested loop: %s", "foobar")
slog.Infof(0, "endloop")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment