| 1 |
package log |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"strings" |
| 6 |
) |
| 7 |
|
| 8 |
// Level is a well-known log level, as defined below |
| 9 |
type Level int |
| 10 |
|
| 11 |
// Well known log levels |
| 12 |
const ( |
| 13 |
TraceLevel Level = iota |
| 14 |
DebugLevel |
| 15 |
InfoLevel |
| 16 |
WarnLevel |
| 17 |
ErrorLevel |
| 18 |
FatalLevel |
| 19 |
) |
| 20 |
|
| 21 |
func (l Level) String() string { |
| 22 |
switch l { |
| 23 |
case TraceLevel: |
| 24 |
return "TRACE" |
| 25 |
case DebugLevel: |
| 26 |
return "DEBUG" |
| 27 |
case InfoLevel: |
| 28 |
return "INFO" |
| 29 |
case WarnLevel: |
| 30 |
return "WARN" |
| 31 |
case ErrorLevel: |
| 32 |
return "ERROR" |
| 33 |
case FatalLevel: |
| 34 |
return "FATAL" |
| 35 |
} |
| 36 |
return "unknown" |
| 37 |
} |
| 38 |
|
| 39 |
// MarshalJSON converts a level to a JSON string |
| 40 |
func (l Level) MarshalJSON() ([]byte, error) { |
| 41 |
return json.Marshal(l.String()) |
| 42 |
} |
| 43 |
|
| 44 |
// ToLevel converts a string to a Level. It returns InfoLevel if the string |
| 45 |
// does not match any known log levels. |
| 46 |
func ToLevel(s string) Level { |
| 47 |
switch strings.ToUpper(s) { |
| 48 |
case "TRACE": |
| 49 |
return TraceLevel |
| 50 |
case "DEBUG": |
| 51 |
return DebugLevel |
| 52 |
case "INFO": |
| 53 |
return InfoLevel |
| 54 |
case "WARN", "WARNING": |
| 55 |
return WarnLevel |
| 56 |
case "ERROR": |
| 57 |
return ErrorLevel |
| 58 |
case "FATAL": |
| 59 |
return FatalLevel |
| 60 |
default: |
| 61 |
return InfoLevel |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
// Format is a well-known log format |
| 66 |
type Format int |
| 67 |
|
| 68 |
// Log formats |
| 69 |
const ( |
| 70 |
TextFormat Format = iota |
| 71 |
JSONFormat |
| 72 |
) |
| 73 |
|
| 74 |
func (f Format) String() string { |
| 75 |
switch f { |
| 76 |
case TextFormat: |
| 77 |
return "text" |
| 78 |
case JSONFormat: |
| 79 |
return "json" |
| 80 |
} |
| 81 |
return "unknown" |
| 82 |
} |
| 83 |
|
| 84 |
// ToFormat converts a string to a Format. It returns TextFormat if the string |
| 85 |
// does not match any known log formats. |
| 86 |
func ToFormat(s string) Format { |
| 87 |
switch strings.ToLower(s) { |
| 88 |
case "text": |
| 89 |
return TextFormat |
| 90 |
case "json": |
| 91 |
return JSONFormat |
| 92 |
default: |
| 93 |
return TextFormat |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
// Contexter allows structs to export a key-value pairs in the form of a Context |
| 98 |
type Contexter interface { |
| 99 |
Context() Context |
| 100 |
} |
| 101 |
|
| 102 |
// Context represents an object's state in the form of key-value pairs |
| 103 |
type Context map[string]any |
| 104 |
|
| 105 |
// Merge merges other into this context |
| 106 |
func (c Context) Merge(other Context) { |
| 107 |
for k, v := range other { |
| 108 |
c[k] = v |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
type levelOverride struct { |
| 113 |
value string |
| 114 |
level Level |
| 115 |
} |