Skip to main content

README.md

1# q.go
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:
10```go
11f, err := os.Stat("maybe_this_file_exists.txt")
12q.Q(err)
13```
15If the first argument is a format string, then the string will be interpolated before it gets logged.
16For example:
18```go
19name := "triangle"
20sides := 3
22q.Q("a %s has %d sides", name, sides)
23// "a triangle has 3 sides"
24```
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`.
29## Inspiration
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:
33```python
34import q; q.q(exc)
35```
37## Example
39Here's a longer example of a program that uses `Q()`:
41```go
42package main
44import (
45 "github.com/alexwlchan/q"
46 "os"
49func printShapeInfo(name string, sides int) {
50 q.Q("a %s has %d sides", name, sides)
53func main() {
54 q.Q("hello world")
56 q.Q(2 + 2)
58 _, err := os.Stat("does_not_exist.txt")
59 q.Q(err)
61 printShapeInfo("triangle", 3)
63```
65And here's what gets written to `/tmp/q.txt`:
67```console
68$ cat /tmp/q.txt
69main: "hello world"
71main: 2 + 2 = 4
73main: err = stat does_not_exist.txt: no such file or directory
75printShapeInfo: a triangle has 3 sides
76```
78## Installation
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!
842. Clone this repo:
86 ```console
87 $ git clone https://github.com/alexwlchan/q.go.git ~/repos/q
88 ```
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:
92 ```console
93 $ mkdir q
94 $ ln -s ~/repos/q/q.go q/q.go
95 ```
974. Add the `q.go` file to your `.git/info/exclude` file, so it will be ignored by Git:
99 ```console
100 $ echo q.go >> .git/info/exclude
101 ```
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.