3This is a Go function for print debugging, where all the printed statements go to a dedicated file.
5The module exports a single function
`Q()`, which you can pass any expression, and it will be logged to the file
`/tmp/q.txt`.
6This means you can log from any goroutine or process, and you can easily find any q-printed statements separate from the rest of your logging.
8Here's a simple example:
11f, err := os.Stat("maybe_this_file_exists.txt")
15If the first argument is a format string, then the string will be interpolated before it gets logged.
22q.Q("a %s has %d sides", name, sides)
23// "a triangle has 3 sides"
26As well as logging the value,
`Q()` logs the name of the calling function, and the expression that you logged.
27For example,
`Q(2 + 2)` will be logged as
`main: 2 + 2 = 4`.
31This idea comes from Ping Yee's [
Python module of the same name](
https://github.com/zestyping/q), which is for quick debugging of Python programs:
39Here's a longer example of a program that uses
`Q()`:
45 "github.com/alexwlchan/q"
49func printShapeInfo(name string, sides int) {
50 q.Q("a %s has %d sides", name, sides)
58 _, err := os.Stat("does_not_exist.txt")
61 printShapeInfo("triangle", 3)
65And here's what gets written to
`/tmp/q.txt`:
73main: err = stat does_not_exist.txt: no such file or directory
75printShapeInfo: a triangle has 3 sides
801. Read the file
`q.go` and make sure you're happy with what it's doing.
81 It's barely a hundred lines of code.
82 Make sure I'm not secretly sending all your logs to my web server!
87 $ git clone https://github.com/alexwlchan/q.go.git ~/repos/q
903. Create a directory
`q` in the root of the project where you want to use this code, and symlink
`q.go` from your checkout:
94 $ ln -s ~/repos/q/q.go q/q.go
974. Add the
`q.go` file to your
`.git/info/exclude` file, so it will be ignored by Git:
100 $ echo q.go >> .git/info/exclude
103This final step allows you to use
`q` in your project, without affecting your coworkers: you don't need to add an entry to your checked in
`.gitignore` or add it to the list of project dependencies.
104It also means you can't check in any leftover debugging code with
`q`, because your tests in CI will immediately fail to compile.