Score:0

In Rsyslog, how do you replace regex matches with custom text?

ky flag

I'm trying to capture text via regular expression and replace the text with a custom string.

My current code successfully captures IP addresses, but I don't know how to replace the IP address with custom text along with the rest of the message:

$Template privateIP,"%TIMESTAMP% %HOSTNAME% %syslogtag% %msg:R,ERE,0,DFLT:([0-9]{1,3}\.){3}[0-9]{1,3}--end%\n"

My first thought is to somehow move the regex out of the template (i.e. with some RainerScript) and create a new field/variable modded_msg that is set to a modified msg property. And then use %modded_msg% in the $Template.

I've tried multiple times (thanks, ChatGPT), but can't get it to work.

Score:0
in flag

The following example can check the msg property for an IP address and then replace all occurrences of it in the message by some string, depending on the address.

set $.myip = re_extract($msg, "(([0-9]{1,3}\\.){3}[0-9]{1,3})", 0, 1, 0);
if ($.myip == 0) then  set $.mymsg = $msg;
else{
 if ($.myip=="192.1.2.3") then
  set $.mymsg = replace($msg, $.myip, "SPECIALIP");
 else
  set $.mymsg = replace($msg, $.myip, "boringip");
}
template(name="mytemplate" type="string" string="%TIMESTAMP% %$.mymsg%\n")
action(type="omfile" file="output" template="mytemplate")

re_extract() looks for the regexp in the property. Note the extra () so we can extract capture group 1, the whole match. Also, the \ is doubled. The last parameter is 0, returned on failure. The returned string is saved in a local variable $.myip.

replace() replaces all occurrences of the string in the property, and returns the result in another local variable. The templace uses this local variable.

Drin avatar
ky flag
Perfect! Thank you so much!
Drin avatar
ky flag
For anyone coming later, it looks like I was originally forgetting to use semicolons on my RainerScript :facepalm:
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.