Forum Discussion
Formating issue: default value for undefined variable
Hello.
We're using an irule to log http access to a remote syslog server. I know there is also a dedicated profile for this, but we prefer to use a consistent implementation for all our logging needs, even those not covered by a profile. In order to ease parsing on SIEM side, I'm emulating standard Combined Log format, which use a dash symbol as a default value when a field is empty, for instance when there is no user name, ie:
foo.domain.tld 127.0.0.1 - - [12/Aug/2019:17:41:02 +0200]
I tried to use a ternary operator directly while formatting the message, ie:
set message [format \
"%s - %s \[%s\]..." \
... \
[[info exists [HTTP::username]] ? [HTTP::username] : '-' ] \
]
However, this syntax triggers a TCL error:
invalid command name "0" while executing "[info exists [HTTP::username]] ? [HTTP::username] : '-' "
I searched TCL documentation for conditional expansion, such as in bash, or default value in the format string, without success.
The only workaround I found was to explicitly define a variable:
if { [info exists [HTTP::username]] } {
set user [HTTP::username]
} else {
set user -
}
This is quite cumbersome, as I have another variable with the same formating issue (the size header in the response).
Is there any other way to achieve the same result in a more compact way ?
You need to make sure you use the expr syntax when using a ternary operator within a variable.
For example:
% set colour [expr {"1" ? "red" : "blue"}] red % set colour [expr {"0" ? "red" : "blue"}] blue
So looking at your example, you'd need to change it to be something like this.. (note that I have changed the from single to double quotation marks for the hyphen)
set message [format \ "%s - %s \[%s\]..." \ ... \ [expr {[info exists [HTTP::username]] ? [HTTP::username] : "-" }] ]
- Lee_SutcliffeNacreous
You need to make sure you use the expr syntax when using a ternary operator within a variable.
For example:
% set colour [expr {"1" ? "red" : "blue"}] red % set colour [expr {"0" ? "red" : "blue"}] blue
So looking at your example, you'd need to change it to be something like this.. (note that I have changed the from single to double quotation marks for the hyphen)
set message [format \ "%s - %s \[%s\]..." \ ... \ [expr {[info exists [HTTP::username]] ? [HTTP::username] : "-" }] ]
- Guillaume_RoussNimbostratus
Indeed. Thanks for the explanation.
Recent Discussions
Related Content
* Getting Started on DevCentral
* Community Guidelines
* Community Terms of Use / EULA
* Community Ranking Explained
* Community Resources
* Contact the DevCentral Team
* Update MFA on account.f5.com