All Projects → sanity-io → Litter

sanity-io / Litter

Licence: mit
Litter is a pretty printer library for Go data structures to aid in debugging and testing.

Programming Languages

go
31211 projects - #10 most used programming language
golang
3204 projects

Projects that are alternatives of or similar to Litter

Structopt
Parse command line arguments by defining a struct
Stars: ✭ 323 (-71.59%)
Mutual labels:  mit-license, library
Logging Log4j2
Apache Log4j 2 is an upgrade to Log4j that provides significant improvements over its predecessor, Log4j 1.x, and provides many of the improvements available in Logback while fixing some inherent problems in Logback's architecture.
Stars: ✭ 1,133 (-0.35%)
Mutual labels:  library, logging
Go Grpc Middleware
Golang gRPC Middlewares: interceptor chaining, auth, logging, retries and more.
Stars: ✭ 4,170 (+266.75%)
Mutual labels:  library, logging
Indicators
Activity Indicators for Modern C++
Stars: ✭ 1,838 (+61.65%)
Mutual labels:  mit-license, library
Tabulate
Table Maker for Modern C++
Stars: ✭ 862 (-24.19%)
Mutual labels:  mit-license, library
Csv
[DEPRECATED] See https://github.com/p-ranav/csv2
Stars: ✭ 237 (-79.16%)
Mutual labels:  mit-license, library
Machineid
Get the unique machine id of any host (without admin privileges)
Stars: ✭ 422 (-62.88%)
Mutual labels:  mit-license, library
Vlog
An in-display logging library for Android 📲
Stars: ✭ 86 (-92.44%)
Mutual labels:  library, logging
Argparse
Argument Parser for Modern C++
Stars: ✭ 680 (-40.19%)
Mutual labels:  mit-license, library
Python Colorlog
A colored formatter for the python logging module
Stars: ✭ 676 (-40.55%)
Mutual labels:  library, logging
Golib
Go Library [DEPRECATED]
Stars: ✭ 194 (-82.94%)
Mutual labels:  library, logging
Belogging
Easy and opinionated logging configuration for Python apps
Stars: ✭ 20 (-98.24%)
Mutual labels:  library, logging
Java Markdown Generator
Java library to generate markdown
Stars: ✭ 159 (-86.02%)
Mutual labels:  library, logging
Pygogo
A Python logging library with superpowers
Stars: ✭ 265 (-76.69%)
Mutual labels:  library, logging
Logsip
A simple, concise, colorful logger for Go
Stars: ✭ 94 (-91.73%)
Mutual labels:  library, logging
Log Process Errors
Show some ❤️ to Node.js process errors
Stars: ✭ 424 (-62.71%)
Mutual labels:  library, logging
Liblognorm
a fast samples-based log normalization library
Stars: ✭ 81 (-92.88%)
Mutual labels:  library, logging
Faster
Fast persistent recoverable log and key-value store + cache, in C# and C++.
Stars: ✭ 4,846 (+326.21%)
Mutual labels:  library, logging
Humblelogging
HumbleLogging is a lightweight C++ logging framework. It aims to be extendible, easy to understand and as fast as possible.
Stars: ✭ 15 (-98.68%)
Mutual labels:  library, logging
Plog
Portable, simple and extensible C++ logging library
Stars: ✭ 1,061 (-6.68%)
Mutual labels:  library, logging

!Build Status

Litter

Litter is a pretty printer library for Go data structures to aid in debugging and testing.


Litter is provided by


Sanity: The Headless CMS Construction Kit

Litter named for the fact that it outputs literals, which you litter your output with. As a side benefit, all Litter output is syntactically correct Go. You can use Litter to emit data during debug, and it's also really nice for "snapshot data" in unit tests, since it produces consistent, sorted output. Litter was inspired by Spew, but focuses on terseness and readability.

Basic example

This:

type Person struct {
	Name   string
	Age    int
	Parent *Person
}

litter.Dump(Person{
	Name:   "Bob",
	Age:    20,
	Parent: &Person{
		Name: "Jane",
		Age:  50,
	},
})

will output:

Person{
	Name: "Bob",
	Age: 20,
	Parent: &Person{
		Name: "Jane",
		Age: 50,
	},
}

Use in tests

Litter is a great alternative to JSON or YAML for providing "snapshots" or example data. For example:

func TestSearch(t *testing.T) {
	result := DoSearch()

	actual := litterOpts.Sdump(result)
	expected, err := ioutil.ReadFile("testdata.txt")
	if err != nil {
		// First run, write test data since it doesn't exist
		if !os.IsNotExist(err) {
			t.Error(err)
		}
		ioutil.Write("testdata.txt", actual, 0644)
		actual = expected
	}
	if expected != actual {
		t.Errorf("Expected %s, got %s", expected, actual)
	}
}

The first run will use Litter to write the data to testdata.txt. On subsequent runs, the test will compare the data. Since Litter always provides a consistent view of a value, you can compare the strings directly.

Circular references

Litter detects circular references or aliasing, and will replace additional references to the same object with aliases. For example:

type Circular struct {
	Self *Circular
}

selfref := Circular{}
selfref.Self = &selfref

litter.Dump(selfref)

will output:

Circular { // p0
	Self: p0,
}

Installation

$ go get -u github.com/sanity-io/litter

Quick start

Add this import line to the file you're working in:

import "github.com/sanity-io/litter"

To dump a variable with full newlines, indentation, type, and aliasing information, use Dump or Sdump:

litter.Dump(myVar1)
str := litter.Sdump(myVar1)

litter.Dump(value, ...)

Dumps the data structure to STDOUT.

litter.Sdump(value, ...)

Returns the dump as a string

Configuration

You can configure litter globally by modifying the default litter.Config

// Strip all package names from types
litter.Config.StripPackageNames = true

// Hide private struct fields from dumped structs
litter.Config.HidePrivateFields = true

// Hide fields matched with given regexp if it is not nil. It is set up to hide fields generate with protoc-gen-go
litter.Config.FieldExclusions = regexp.MustCompile(`^(XXX_.*)$`)

// Sets a "home" package. The package name will be stripped from all its types
litter.Config.HomePackage = "mypackage"

// Sets separator used when multiple arguments are passed to Dump() or Sdump().
litter.Config.Separator = "\n"

// Use compact output: strip newlines and other unnecessary whitespace
litter.Config.Compact = true

// Prevents duplicate pointers from being replaced by placeholder variable names (except in necessary, in the case
// of circular references)
litter.Config.DisablePointerReplacement = true

litter.Options

Allows you to configure a local configuration of litter to allow for proper compartmentalization of state at the expense of some comfort:

	sq := litter.Options {
		HidePrivateFields: true,
		HomePackage: "thispack",
		Separator: " ",
	}

	sq.Dump("dumped", "with", "local", "settings")

Custom dumpers

Implement the interface Dumper on your types to take control of how your type is dumped.

type Dumper interface {
	LitterDump(w io.Writer)
}

Just write your custom dump to the provided stream, using multiple lines divided by "\n" if you need. Litter might indent your output according to context, and optionally decorate your first line with a pointer comment where appropriate.

A couple of examples from the test suite:

type CustomMultiLineDumper struct {}

func (cmld *CustomMultiLineDumper) LitterDump(w io.Writer) {
	w.Write([]byte("{\n  multi\n  line\n}"))
}

type CustomSingleLineDumper int

func (csld CustomSingleLineDumper) LitterDump(w io.Writer) {
	w.Write([]byte("<custom>"))
}
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].