浏览代码

Updated with info about passing callable

Alois Mahdal 11 年前
父节点
当前提交
ca04c32a8d
共有 1 个文件被更改,包括 51 次插入0 次删除
  1. 51
    0
      README.md

+ 51
- 0
README.md 查看文件

@@ -204,3 +204,54 @@ APIs to make usage of *htlog.cgi* in Perl and Python scripts even easier
204 204
         );
205 205
 
206 206
     }
207
+
208
+Note that htlogr also supports passing of callable code instead of `i` or
209
+`tag`.  Use this if you find yourself constructing them in a non-trivial
210
+way before every call.
211
+
212
+I'll illustrate this with Python API, but of course implementation and use
213
+is same in both APIs.
214
+
215
+Imagine situation when existence of a certain environment variable tells us
216
+context in which we are running (e.g. a specific test case) and its value
217
+is the iteration (e.g. Jenkins build number).
218
+
219
+This example examines environment for existence of such variable and then
220
+uses its name as tag and value as i.
221
+
222
+The code:
223
+
224
+    import htlogr
225
+    import os
226
+
227
+    logger = htlogr('http://192.168.1.1/cgi-bin/htlog.cgi')
228
+
229
+    def get_both():
230
+        for key in ['var1', 'var2']:
231
+            try:
232
+                return os.environ[key], key
233
+            except KeyError:
234
+                pass
235
+
236
+    def get_i():
237
+        i, tag = get_both()
238
+        return i
239
+
240
+    def get_tag():
241
+        i, tag = get_both()
242
+        return tag
243
+
244
+    logger.log("hello", tag=get_tag, i=get_i)
245
+
246
+Now you can e.g. write a logging wrapper function in a trivial yet flexible way:
247
+
248
+    # inside a class:
249
+
250
+    def rmsg(self, mesage):
251
+        self.logger.log(message, i=self.get_i, tag=self.name)
252
+
253
+    def rwarn(self, mesage):
254
+        self.logger.log('warning: ' message, i=self.get_i, tag=self.name)
255
+
256
+    def rstats(self, stats):
257
+        self.logger.data(stats, i=self.get_i, tag=self.name)