We've started using Serilog to generate structure logs for our application. Using Serilog Expressions we've been able to generate the following JSON, which is fairly cool as far as logging goes.
{
"@t": "2022-02-11T15:57:57.6087361+01:00",
"@m": "GET Request received on API endpoint /foo",
"@l": "Info",
"SourceContext": "Company.API.FooController",
"ActionId": "bd248542-138b-4053-9d50-b9e62e0ab1fd",
"ActionName": "Company.API.FooController.GetFoo (Company.API)",
"RequestId": "0HMFDDRDSMUUI:00000001",
"RequestPath": "/foo",
"SpanId": "|85c9c2db-489a260ce2c6915e.",
"TraceId": "85c9c2db-489a260ce2c6915e",
"ParentId": "",
"ConnectionId": "0HMFDDRDSMUUI",
"ThreadId": 7,
"ContextFieldA": "ValueA",
"ContextFieldB": "ValueA"
}
These log events are generated using the following expression, which is read from the environment variables:
"{ {@t, @m, @r, @l: if @l = 'Information' then 'Info' else @l, @x, ..@p} }\n"
However we'd like to map the other log levels to short-hands as well. Such as Warning
to Warn
etc. How would we go about adding multiple if-else branches to this expression?
The answer is surprisingly simple actually. Multiple branches can be done exactly like one might expect:
"{ {@t, @m, @r, @l: if @l = 'Information' then 'Info'
else if @l = 'Warning' then 'Warn' else @l, @x, ..@p} }\n"