• Stars
    star
    1,901
  • Rank 23,420 (Top 0.5 %)
  • Language
    Go
  • License
    MIT License
  • Created over 1 year ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A minimal, colorful Go logging library ๐Ÿชต

Log


Latest Release Go Docs Build Status Codecov branch Go Report Card

A minimal and colorful Go logging library. ๐Ÿชต

Made with VHS

It provides a leveled structured human readable logger with a small API. Unlike standard log, the Charm logger provides customizable colorful human readable logging with batteries included.

  • Uses Lip Gloss to style and colorize the output.
  • Colorful, human readable format.
  • Ability to customize the time stamp format.
  • Skips caller frames and marks function as helpers.
  • Leveled logging.
  • Text, JSON, and Logfmt formatters.
  • Store and retrieve logger in and from context.
  • Standard log adapter.

Usage

Use go get to download the dependency.

go get github.com/charmbracelet/log@latest

Then, import it in your Go files:

import "github.com/charmbracelet/log"

The Charm logger comes with a global package-wise logger with timestamps turned on, and the logging level set to info.

log.Debug("Cookie ๐Ÿช") // won't print anything
log.Info("Hello World!")
Made with VHS

All logging levels accept optional key/value pairs to be printed along with a message.

err := fmt.Errorf("too much sugar")
log.Error("failed to bake cookies", "err", err)
Made with VHS

You can use log.Print() to print messages without a level prefix.

log.Print("Baking 101")
// 2023/01/04 10:04:06 Baking 101

New loggers

Use New() to create new loggers.

logger := log.New(os.Stderr)
if butter {
    logger.Warn("chewy!", "butter", true)
}

Levels

Log offers multiple levels to filter your logs on. Available levels are:

log.DebugLevel
log.InfoLevel
log.WarnLevel
log.ErrorLevel
log.FatalLevel

Use log.SetLevel() to set the log level. You can also create a new logger with a specific log level using log.Options{Level: }.

Use the corresponding function to log a message:

err := errors.New("Baking error 101")
log.Debug(err)
log.Info(err)
log.Warn(err)
log.Error(err)
log.Fatal(err) // this calls os.Exit(1)
log.Print(err) // prints regardless of log level

Or use the formatter variant:

format := "%s %d"
log.Debugf(format, "chocolate", 10)
log.Warnf(format, "adding more", 5)
log.Errorf(format, "increasing temp", 420)
log.Fatalf(format, "too hot!", 500) // this calls os.Exit(1)
log.Printf(format, "baking cookies") // prints regardless of log level

// Use these in conjunction with `With(...)` to add more context
log.With("err", err).Errorf("unable to start %s", "oven")

Structured

All the functions above take a message and key-value pairs of anything. The message can also be of type any.

ingredients := []string{"flour", "butter", "sugar", "chocolate"}
log.Debug("Available ingredients", "ingredients", ingredients)
// DEBUG Available ingredients ingredients="[flour butter sugar chocolate]"

Options

You can customize the logger with options. Use log.NewWithOptions() and log.Options{} to customize your new logger.

logger := log.NewWithOptions(os.Stderr, log.Options{
    ReportCaller: true,
    ReportTimestamp: true,
    TimeFormat: time.Kitchen,
    Prefix: "Baking ๐Ÿช "
})
logger.Info("Starting oven!", "degree", 375)
time.Sleep(10 * time.Minute)
logger.Info("Finished baking")

You can also use logger setters to customize the logger.

logger := log.New(os.Stderr)
logger.SetReportTimestamp(false)
logger.SetReportCaller(false)
logger.SetLevel(log.DebugLevel)

Use log.SetFormatter() or log.Options{Formatter: } to change the output format. Available options are:

  • log.TextFormatter (default)
  • log.JSONFormatter
  • log.LogfmtFormatter

Note styling only affects the TextFormatter. Styling is disabled if the output is not a TTY.

For a list of available options, refer to options.go.

Styles

You can customize the logger styles using Lipgloss. The styles are defined at a global level in styles.go.

// Override the default error level style.
log.ErrorLevelStyle = lipgloss.NewStyle().
    SetString("ERROR!!").
    Padding(0, 1, 0, 1).
    Background(lipgloss.AdaptiveColor{
        Light: "203",
        Dark:  "204",
    }).
    Foreground(lipgloss.Color("0"))
// Add a custom style for key `err`
log.KeyStyles["err"] = lipgloss.NewStyle().Foreground(lipgloss.Color("204"))
log.ValueStyles["err"] = lipgloss.NewStyle().Bold(true)
log.Error("Whoops!", "err", "kitchen on fire")

Sub-logger

Create sub-loggers with their specific fields.

logger := log.NewWithOptions(os.Stderr, log.Options{
    Prefix: "Baking ๐Ÿช "
})
batch2 := logger.With("batch", 2, "chocolateChips", true)
batch2.Debug("Preparing batch 2...")
batch2.Debug("Adding chocolate chips")

Format Messages

You can use fmt.Sprintf() to format messages.

for item := 1; i <= 100; i++ {
    log.Info(fmt.Sprintf("Baking %d/100...", item))
}

Or arguments:

for temp := 375; temp <= 400; temp++ {
    log.Info("Increasing temperature", "degree", fmt.Sprintf("%dยฐF", temp))
}

Helper Functions

Skip caller frames in helper functions. Similar to what you can do with testing.TB().Helper().

function startOven(degree int) {
    log.Helper()
    log.Info("Starting oven", "degree", degree)
}

log.SetReportCaller(true)
startOven(400) // INFO <cookies/oven.go:123> Starting oven degree=400

This will use the caller function (startOven) line number instead of the logging function (log.Info) to report the source location.

Standard Log Adapter

Some Go libraries, especially the ones in the standard library, will only accept the standard logger interface. For instance, the HTTP Server from net/http will only take a *log.Logger for its ErrorLog field.

For this, you can use the standard log adapter, which simply wraps the logger in a *log.Logger interface.

logger := log.NewWithOptions(os.Stderr, log.Options{Prefix: "http"})
stdlog := logger.StandardLog(log.StandardLogOptions{
    ForceLevel: log.ErrorLevel,
})
s := &http.Server{
    Addr:     ":8080",
    Handler:  handler,
    ErrorLog: stdlog,
}
stdlog.Printf("Failed to make bake request, %s", fmt.Errorf("temperature is too low"))
// ERROR http: Failed to make bake request, temperature is too low

License

MIT


Part of Charm.

the Charm logo

Charm็ƒญ็ˆฑๅผ€ๆบ โ€ข Charm loves open source โ€ข ู†ุญู†ู ู†ุญุจ ุงู„ู…ุตุงุฏุฑ ุงู„ู…ูุชูˆุญุฉ

More Repositories

1

bubbletea

A powerful little TUI framework ๐Ÿ—
Go
23,251
star
2

gum

A tool for glamorous shell scripts ๐ŸŽ€
Go
16,385
star
3

glow

Render markdown on the CLI, with pizzazz! ๐Ÿ’…๐Ÿป
Go
14,499
star
4

vhs

Your CLI home video recorder ๐Ÿ“ผ
Go
13,375
star
5

lipgloss

Style definitions for nice terminal layouts ๐Ÿ‘„
Go
7,073
star
6

soft-serve

The mighty, self-hostable Git server for the command line๐Ÿฆ
Go
4,638
star
7

bubbles

TUI components for Bubble Tea ๐Ÿซง
Go
4,509
star
8

huh

Build terminal forms and prompts ๐Ÿคท๐Ÿปโ€โ™€๏ธ
Go
2,956
star
9

wish

Make SSH apps, just like that! ๐Ÿ’ซ
Go
2,816
star
10

mods

AI on the command line
Go
2,261
star
11

charm

The Charm Tool and Library ๐ŸŒŸ
Go
2,177
star
12

glamour

Stylesheet-based markdown rendering for your CLI apps ๐Ÿ’‡๐Ÿปโ€โ™€๏ธ
Go
2,057
star
13

pop

Send emails from your terminal ๐Ÿ“ฌ
Go
2,044
star
14

skate

A personal key value store ๐Ÿ›ผ
Go
1,167
star
15

wishlist

The SSH directory โœจ
Go
959
star
16

harmonica

A simple, physics-based animation library ๐ŸŽผ
Go
945
star
17

melt

๐ŸงŠ Backup and restore Ed25519 SSH keys with seed words.
Go
418
star
18

kancli

A tutorial for building a command line kanban board in Go
Go
155
star
19

vhs-action

Keep your GIFs up to date with VHS + GitHub actions ๐Ÿ“ฝ๏ธ
TypeScript
141
star
20

keygen

An SSH key pair generator ๐Ÿ—๏ธ
Go
101
star
21

bubbletea-app-template

A template repository to create Bubbletea apps.
Go
99
star
22

inspo

Share and explore projects you can build with Charm libraries
87
star
23

taskcli

A tutorial for building a Taskwarrior-inspired task tracker in Go using glamorous CLI libraries
Go
77
star
24

wizard-tutorial

A basic wizard made with Bubble Tea and Lip Gloss. Follow along with the tutorial video for this project:
Go
73
star
25

tree-sitter-vhs

Syntax highlighting for VHS with tree-sitter ๐ŸŒณ
C
69
star
26

x

Charm experimental packages.
Go
65
star
27

confettysh

confetti over ssh
Go
49
star
28

catwalk

Open source 3D models from Charm ๐Ÿงธ
49
star
29

soft-serve-action

Synchronize GitHub repositories to your Soft Serve instance ๐Ÿฆ
43
star
30

git-lfs-transfer

Server-side implementation of the Git LFS pure-SSH protocol
Go
42
star
31

promwish

Prometheus middleware for Wish
Go
37
star
32

meta

Charm's meta configuration files ๐Ÿซฅ
23
star
33

homebrew-tap

Our homebrew tap ๐Ÿบ
Ruby
21
star
34

scoop-bucket

Charmbracelet Scoop Bucket
14
star
35

nur

Nix
13
star
36

.github

1
star