added functions is_interesting_count and n_digits to log_helpers
authorChristian Herdtweck <christian.herdtweck@intra2net.com>
Mon, 30 Nov 2015 09:11:59 +0000 (10:11 +0100)
committerChristian Herdtweck <christian.herdtweck@intra2net.com>
Mon, 30 Nov 2015 09:11:59 +0000 (10:11 +0100)
log_helpers.py

index ee90329..605febb 100644 (file)
@@ -32,6 +32,7 @@ Further ideas: ::
 
 import logging
 from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL, NOTSET
+from math import log10, floor
 
 #: log level half-way between INFO and WARNING
 NOTICE = (INFO + WARNING)/2
@@ -207,6 +208,42 @@ class I2nLogger:
             handler.setLevel(self._level)
 
 
+def n_digits(number):
+    """ returns the number of digits a number has in decimal format
+
+    :returns: 1 for 1...9, 2 for 10...99, 3 for 100...999, ...
+              0 for 0 (and everything else beween -1 and 1)
+              1 for -1...-9, 2 for -10...-99, ...
+    """
+    if abs(number) < 1:
+        return 0
+    else:
+        return floor(log10(abs(number)))+1
+
+
+def is_interesting_count(counter):
+    """ return True if counter has reached an "interesting" value
+
+    For the counter to be "interesting" becomes ever harder. At first it is
+    easy (returns True for 1,2,3,6,10), then becomes harder (True only for
+    10,20,30,60,100) and harder (True for 100,200,300,600,1000) and this scheme
+    continues on a logartihmic scale.
+
+    An example that will print lots in the beginning and then less and less::
+
+        counter = 0
+        while not end_reached():
+            do_something()
+            if is_interesting_count(counter):
+                log('reached iteration {0}'.format(counter))
+            counter += 1
+
+    :returns: True for a few values of counter, False most of the time
+    """
+
+    return float(counter) / 10.**(n_digits(counter)-1.) in (1.,2.,3.,6.)
+
+
 def test_short_level_format():
     """ quick test of :py:class:`ShortLevelFormatter` """