MCPcopy
hub / github.com/op/go-logging / NewStringFormatter

Function NewStringFormatter

format.go:199–258  ·  view source on GitHub ↗

NewStringFormatter returns a new Formatter which outputs the log record as a string based on the 'verbs' specified in the format string. The verbs: General: %{id} Sequence number for log message (uint64). %{pid} Process id (int) %{time} Time when log occurred (time.Time) %{level}

(format string)

Source from the content-addressed store, hash-verified

197// %{shortfunc} Base function name, eg. PutUint32
198// %{callpath} Call function path, eg. main.a.b.c
199func NewStringFormatter(format string) (Formatter, error) {
200 var fmter = &stringFormatter{}
201
202 // Find the boundaries of all %{vars}
203 matches := formatRe.FindAllStringSubmatchIndex(format, -1)
204 if matches == nil {
205 return nil, errors.New("logger: invalid log format: " + format)
206 }
207
208 // Collect all variables and static text for the format
209 prev := 0
210 for _, m := range matches {
211 start, end := m[0], m[1]
212 if start > prev {
213 fmter.add(fmtVerbStatic, format[prev:start])
214 }
215
216 name := format[m[2]:m[3]]
217 verb := getFmtVerbByName(name)
218 if verb == fmtVerbUnknown {
219 return nil, errors.New("logger: unknown variable: " + name)
220 }
221
222 // Handle layout customizations or use the default. If this is not for the
223 // time, color formatting or callpath, we need to prefix with %.
224 layout := defaultVerbsLayout[verb]
225 if m[4] != -1 {
226 layout = format[m[4]:m[5]]
227 }
228 if verb != fmtVerbTime && verb != fmtVerbLevelColor && verb != fmtVerbCallpath {
229 layout = "%" + layout
230 }
231
232 fmter.add(verb, layout)
233 prev = end
234 }
235 end := format[prev:]
236 if end != "" {
237 fmter.add(fmtVerbStatic, end)
238 }
239
240 // Make a test run to make sure we can format it correctly.
241 t, err := time.Parse(time.RFC3339, "2010-02-04T21:00:57-08:00")
242 if err != nil {
243 panic(err)
244 }
245 testFmt := "hello %s"
246 r := &Record{
247 ID: 12345,
248 Time: t,
249 Module: "logger",
250 Args: []interface{}{"go"},
251 fmt: &testFmt,
252 }
253 if err := fmter.Format(0, r, &bytes.Buffer{}); err != nil {
254 return nil, err
255 }
256

Callers 2

TestFormatFunction · 0.85
MustStringFormatterFunction · 0.85

Calls 3

getFmtVerbByNameFunction · 0.85
addMethod · 0.80
FormatMethod · 0.65

Tested by 1

TestFormatFunction · 0.68