tlog.app/go/tlog@v0.23.1/examples/charmlog/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "os" 6 "time" 7 8 "tlog.app/go/tlog" 9 "tlog.app/go/tlog/tlwire" 10 ) 11 12 const ( 13 Cups = tlog.SemanticUserBase + iota 14 ) 15 16 type cup int 17 18 func (c cup) String() string { 19 s := fmt.Sprintf("%d cup", c) 20 if c > 1 { 21 s += "s" 22 } 23 return s 24 } 25 26 // TlogAppend overrides the default String() encoding. 27 // It's useful for making it machine-readable. 28 func (c cup) TlogAppend(b []byte) []byte { 29 var e tlwire.Encoder 30 b = e.AppendSemantic(b, Cups) 31 b = e.AppendInt(b, int(c)) 32 return b 33 } 34 35 func before() { 36 w := tlog.NewConsoleWriter(os.Stderr, tlog.Ltime|tlog.Lloglevel) 37 38 tlog.DefaultLogger = tlog.New(w) 39 40 tlog.SetVerbosity("oven,ingredients") // enable debug logs; precisely 41 } 42 43 func startOven(degree int) { 44 tlog.V("oven").NewMessage(1, tlog.ID{}, "Starting oven", 45 "temperature", degree, 46 tlog.KeyLogLevel, tlog.Debug, // not idiomatic, but possible 47 ) 48 } 49 50 // charmlog example rewritten in tlog 51 // 52 // https://github.com/charmbracelet/log/blob/2d80948d38ad30d727aed3a1984f4a4911203019/examples/app/main.go 53 func main() { 54 before() 55 56 var ( 57 butter = cup(1) 58 chocolate = cup(2) 59 flour = cup(3) 60 sugar = cup(5) 61 temp = 375 62 bakeTime = 10 * time.Minute 63 ) 64 65 startOven(temp) 66 time.Sleep(time.Second) 67 68 // Will not be printed if "ingredients" debug topic is not selected. 69 // No allocs made in both cases, that is why the interface is a bit nerdy. 70 tlog.V("ingredients").Printw("Mixing ingredients", "ingredients", 71 tlog.RawTag(tlwire.Map, 4), // idiomatic way is to use flat structure, 72 "butter", butter, // but possible to have as complex structure as you need 73 "chocolate", chocolate, 74 "flour", flour, 75 "sugar", sugar, 76 77 "", tlog.LogLevel(-3), // not idiomatic, but can even have multiple levels of debug (this is third) 78 ) 79 80 time.Sleep(time.Second) 81 82 if sugar > 2 { 83 tlog.Printw("That's a lot of sugar", "amount", sugar, "", tlog.Warn) // the "" key means it's guessed by value type 84 } 85 86 tlog.Printw("Baking cookies", "time", bakeTime) 87 88 time.Sleep(2 * time.Second) 89 90 tlog.Printw("Increasing temperature", "amount", 300) 91 92 temp += 300 93 time.Sleep(time.Second) 94 95 if temp > 500 { 96 tlog.Printw("Oven is too hot", "temperature", temp, "", tlog.Error) 97 tlog.Printw("The kitchen is on fire 🔥", "", tlog.Fatal) 98 os.Exit(1) 99 } 100 }