Grafana line_format multiple variable

Hello everyone,

I am creating a variable called show in Grafana. With this I am pulling label names from Loki as below. In this way, information such as Message, Level, File, job of my logs, which I send in the form of regex with promtail, comes.


I want to have a query like “{hostname=“my_host”} | line_format “{{.$show}}””. If I select only Level from the show variable, the Level information of the logs will be seen. If I select Level, File, Message, this information will be seen. For example;

But when I try to do it multiple times I get an error.
I guess it doesn’t add a period to the second word, but when I type it by hand (For example “{{.Level|.Log_Time}}”) it doesn’t work very well either. Can you help me?

This is an interesting use case. I don’t think it’s a good idea personally though.

I can’t think of an elegant way to achieve this, but if you really want it you may be able to do it with a line_format template with a lot of hardcoding.

Let’s say you have Level, File, and Message, you could do something like this (I don’t know if the variable substitute actually works, but let’s assume it does):

  | line_format `{{ if eq $Show "Level" }}{{.Level}}{{else if eq $Show "Level|File"}}{{.Level}}{{.File}}{{else if eq $Show "*"}}{{.Level}}{{.File}}{{.Message}} ... <MORE IF/ELSE> ... {{end}}`

It would be much easier if the template supports regex (which I don’t think it does). You can also simplify this a bit yourself by having some presets, for example preset one means show level and message, preset two shows file and message, preset three shows everything, and so on.

Thanks for your help, but I’m getting an error like this:

rpc error: code = Unknown desc = parse error : stage '| line_format "{{ if eq File \"File\" }}{{.File}}{{else if eq File \"Level|File\"}}{{.Level}}{{.File}}{{else if eq File \"Log_Time\"}}{{.Level}}{{.File}}{{.Message}}{{end}}"' : invalid line template: template: line:1: function "File" not defined

Probably simply that a bit to just one if condition, then gradually expand.

It worked correctly with a usage like this:

{instance=~"$host"} | logfmt  | line_format "{{if eq \"Level\" \"$show\"}}{{.Messages}}    {{else if eq \"ID\" \"$show\"}}{{.ID}}    {{else if eq \"ID|Level\" \"$show\"}}{{.ID}} {{.Level}}    {{else}}{{.Log_Time}} {{.Level}}{{end}}"

However; In this case too, I have to write many “else if” conditions. It looks like I can’t do it by selecting the variable.