Linux – Using Environment Variable in rsyslog Template

log-filesloggingrsyslogsyslogUbuntu

I'm trying to add an environment variable to my rsyslog template.
I tried using 'getenv()' function without any luck, I always get an empty string in return.

I'm attaching an example of my rsyslog config file, I'm using 'HOME' env variable as an example.

/etc/rsyslog.d/00-my_log.conf

set $.my_home=getenv("HOME");

template(name="json-template"
  type="list") {
    constant(value="{")
      constant(value="\",\"my_home\":\"")     property(name="$.my_home")
      constant(value="\",\"message\":\"")     property(name="msg" format="json")
    constant(value="\"}\n")
}

*.* action(type="omfile" dirCreateMode="0700" FileCreateMode="0644"
       template="json-template" File="/var/log/my_log")

/var/log/my_log

{"my_home":"","message":"my log message"}

rsyslogd: version 8.4.2

Best Answer

i was able to use this guidance rsyslog: Specify `action` parameters from environment variables

to shell out from the config file to get the environment variables in the template:

template(name="logfile" type="list") {
   constant(value="{")

   constant(value="\"@timestamp\":\"")     
   property(name="timegenerated" dateFormat="rfc3339")
   constant(value="\", ")
   
   constant(value="\"pod_namespace\":\"")     
   constant(value=`echo $KUB_POD_NAMESPACE`)
   constant(value="\", ")
   
   constant(value="\"pod_name\":\"")     
   constant(value=`echo $KUB_POD_NAME`)
   constant(value="\", ")
   
   constant(value="\"pod_ip\":\"")     
   constant(value=`echo $KUB_INSTANCE_ADDR`)
   constant(value="\", ")
   
   property(name="$!all-json" position.from="2")
}