Home > Back-end >  Ruby Regex exclude if doest exist
Ruby Regex exclude if doest exist

Time:10-04

I have been trying to parse my app logs with this Ruby Regex:

^time="?(?<timeapp>.*?)"? level="?(?<loglevel>.*?)"? msg="?(?<log>.*)"? trace-id=?(?<trace_id>.*?)$

The log is:

time="2022-09-29T13:47:57Z" level=info msg="[AP] SKU:prem_30d_01.09.2018_1065_2_offer_trial, userID:202222" guid=cFhblwnH5 trace-id=75dddd-EFW

Buy Ive faced a problem that trace-id= is not always in logs. Cannot find how to exclude trace-id parsing IF it doesn't exist in logs

https://rubular.com/r/NblAOyyZbvXaDW

CodePudding user response:

In your code you are looking for a space character after your msg group:

msg="?(?<log>.*)"? trace-id=

(so right between the ? and t from trace). I imagine that if trace is not present, neither is that space character so thats why it doesnt match. Making that space character optional, say with \s? would lead to your msg= group being greedy and grabbing everything, regardless of whether its there or not.

this might not be the best solution, as instead of matching any character i just limited it to the ones you would expect ([a-zA-Z\[\]0-9\"=:_\.,\s]):

^time="?(?<timeapp>.*?)"? level="?(?<loglevel>.*?)"? msg="?(?<log>[a-zA-Z\[\]0-9\"=:_\.,\s]*)"?(\strace-id=?(?<trace_id>.*?))?$
  •  Tags:  
  • ruby
  • Related