Debian Codegraph @

pkg/types/message_item.go

raw
1 package types
2
3 import (
4 "strings"
5 "time"
6 )
7
8 // MessageLevel is used to denote the urgency of a message item.
9 type MessageLevel uint8
10
11 // File represents a file attachment for a message.
12 type File struct {
13 Name string
14 Data []byte
15 }
16
17 // MessageItem is an entry in a notification being sent by a service.
18 type MessageItem struct {
19 Text string
20 Timestamp time.Time
21 Level MessageLevel
22 Fields []Field
23 File *File
24 }
25
26 const (
27 // Unknown is the default message level.
28 Unknown MessageLevel = iota
29 // Debug is the lowest kind of known message level.
30 Debug
31 // Info is generally used as the "normal" message level.
32 Info
33 // Warning is generally used to denote messages that might be OK, but can cause problems.
34 Warning
35 // Error is generally used for messages about things that did not go as planned.
36 Error
37 messageLevelCount
38 )
39
40 // MessageLevelCount is used to create arrays that maps levels to other values.
41 const MessageLevelCount = int(messageLevelCount)
42
43 var messageLevelStrings = [MessageLevelCount]string{
44 "Unknown",
45 "Debug",
46 "Info",
47 "Warning",
48 "Error",
49 }
50
51 func (lvl MessageLevel) String() string {
52 if lvl >= messageLevelCount {
53 return messageLevelStrings[0]
54 }
55
56 return messageLevelStrings[lvl]
57 }
58
59 // WithField appends the key/value pair to the message items fields.
60 func (mi *MessageItem) WithField(key, value string) *MessageItem {
61 mi.Fields = append(mi.Fields, Field{
62 Key: key,
63 Value: value,
64 })
65
66 return mi
67 }
68
69 // ItemsToPlain joins together the MessageItems' Text using newlines.
70 // Used implement the rich sender API by redirecting to the plain sender implementation.
71 func ItemsToPlain(items []MessageItem) string {
72 builder := strings.Builder{}
73 for _, item := range items {
74 builder.WriteString(item.Text)
75 builder.WriteRune('\n')
76 }
77
78 return builder.String()
79 }