Log Every X Seconds

Problem this snippet solves:

Version 10.1 CMP Compatible Update by: David Homoney - Senior Consultant F5 Networks - d.homoney (at) f5 (dot) com

This example shows how to throttle log messages so a message is only logged every X number of seconds. This can be used to lower the amount of CPU time alertd uses when performing logging.

How to use this snippet:

Here is a CMP-compliant version written for use with version 10.1.0 or higher. This example utilizes the table command and STATIC name space to make this CMP compatible

Code :

when RULE_INIT {
   
   # Shortest interval (in seconds) to log a message
   set static::min_log_interval 60
   set static::key "last_log_timestamp"
}
when CLIENT_ACCEPTED {

   if  {[active_members [LB::server pool]] < 3}{

      set lastlog [table lookup -subtable $static::sub_table $static::key]
      set now [clock seconds]
      if { $lastlog equals "" }{
         # This is the first execution so create the table entry and force a log attempt
         table add $static::key $now indef indef
         set lastlog 0
      }
      if {[expr { ($now - $lastlog) > $static::min_log_interval }]}{
         log local0. "[virtual], [LB::server pool]: [active_members [LB::server pool]] members available!"
         table replace $static::key $now indef indef
      }
   }
}

# Here's an old pre-10.x version (which is not CMP compatible!):

when RULE_INIT {

   # Initialize a variable to track the last time a log message was made
   set ::last_log_timestamp [clock seconds]

   # Shortest interval (in seconds) to log a message
   set ::min_log_interval 60
}
when CLIENT_ACCEPTED {

   # Note: these two if statements should probably be reversed for a real iRule.
   #   but for this example, I'm using the clock check first.


   # Check if the log interval has passed
   if {[expr {[clock seconds] - $::last_log_timestamp}] > $::min_log_interval}{

      # Check if there are two or less active members in the default pool
      if {[active_members [LB::server pool]] < 3}{

         log local0. "[virtual name], [LB::server pool]: [active_members [LB::server pool]] members available!"

         # Update the last run timestamp
         set ::last_log_timestamp [clock seconds]
      }
   }
}
Published Mar 18, 2015
Version 1.0

Was this article helpful?

No CommentsBe the first to comment