NewFormatter builds a new instance of event's formatter.
(template string)
| 117 | |
| 118 | // NewFormatter builds a new instance of event's formatter. |
| 119 | func NewFormatter(template string) (*Formatter, error) { |
| 120 | // check basic template format and ensure all fields |
| 121 | // defined in the template are known to us |
| 122 | flds := tmplRegexp.FindAllStringSubmatch(template, -1) |
| 123 | if len(flds) == 0 { |
| 124 | return nil, fmt.Errorf("invalid template format: %q", template) |
| 125 | } |
| 126 | if ok, pos := isTemplateBalanced(template); !ok { |
| 127 | return nil, fmt.Errorf("template syntax error near field #%d: %q", pos, template) |
| 128 | } |
| 129 | |
| 130 | for i, field := range flds { |
| 131 | if len(field) > 0 { |
| 132 | name := sanitize(field[0]) |
| 133 | if strings.HasPrefix(name, parsAccessor) { |
| 134 | continue |
| 135 | } |
| 136 | if name == "" { |
| 137 | return nil, fmt.Errorf("empty field found at position %d", i+1) |
| 138 | } |
| 139 | if _, ok := fields[name]; !ok { |
| 140 | return nil, fmt.Errorf("%s is not a known field name. Maybe you meant one "+ |
| 141 | "of the following fields: %s", name, hintFields()) |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | // user might define the tag such as `{{ .Seq }}` or {{ .Seq}}`. We have to make sure |
| 147 | // inner spaces are removed before building the fast template instance |
| 148 | norm := normalizeTemplate(template) |
| 149 | t, err := fasttemplate.NewTemplate(norm, startTag, endTag) |
| 150 | if err != nil { |
| 151 | return nil, fmt.Errorf("invalid template format %q: %v", norm, err) |
| 152 | } |
| 153 | |
| 154 | return &Formatter{ |
| 155 | t: t, |
| 156 | expandParamsDot: tmplExpandParamsRegexp.MatchString(norm), |
| 157 | }, nil |
| 158 | } |
| 159 | |
| 160 | // ColorFormatter wraps a Formatter and re-renders each template tag with |
| 161 | // ANSI colour codes before it is substituted into the output string. |