From b45c58e3aee695d536fd52c617508f4bd983d633 Mon Sep 17 00:00:00 2001 From: Avleen Vig Date: Fri, 27 Feb 2015 18:34:10 +0000 Subject: [PATCH] Add support to log a full buffer and TTL expiry to syslog. --- expiringdict/__init__.py | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/expiringdict/__init__.py b/expiringdict/__init__.py index 3e2f298..ad49590 100644 --- a/expiringdict/__init__.py +++ b/expiringdict/__init__.py @@ -4,7 +4,7 @@ Expiration happens on any access, object is locked during cleanup from expired values. Can not store more than max_len elements - the oldest will be deleted. ->>> ExpiringDict(max_len=100, max_age_seconds=10) +>>> ExpiringDict(max_len=100, max_age_seconds=10, logging=False) The values stored in the following way: { @@ -15,6 +15,7 @@ NOTE: iteration over dict and also keys() do not remove expired values! ''' +import syslog import time from threading import RLock @@ -26,7 +27,7 @@ class ExpiringDict(OrderedDict): - def __init__(self, max_len, max_age_seconds): + def __init__(self, max_len, max_age_seconds, logging=False): assert max_age_seconds >= 0 assert max_len >= 1 @@ -34,6 +35,9 @@ def __init__(self, max_len, max_age_seconds): self.max_len = max_len self.max_age = max_age_seconds self.lock = RLock() + self.logging = logging + if logging: + self.setup_syslog() def __contains__(self, key): """ Return True if the dict has a key, else return False. """ @@ -62,6 +66,7 @@ def __getitem__(self, key, with_age=False): else: return item[0] else: + self.log_expired(key, item[0]) del self[key] raise KeyError(key) @@ -80,6 +85,7 @@ def pop(self, key, default=None): with self.lock: try: item = OrderedDict.__getitem__(self, key) + self.log_full(key, item[0]) del self[key] return item[0] except KeyError: @@ -151,3 +157,19 @@ def viewkeys(self): def viewvalues(self): """ Return a new view of the dictionary's values. """ raise NotImplementedError() + + def setup_syslog(self): + """ Set options for syslog. """ + syslog.openlog('expiringdict') + + def log_expired(self, key, value): + """ Log that we deleted an expired key. """ + if self.logging: + syslog.syslog("Deleting expired entry. " + "Key: %s, value: %s" % (key, value)) + + def log_full(self, key, value): + """ Log that we deleted the oldest key. """ + if self.logging: + syslog.syslog("Deleting entry due to full cache. " + "Key: %s, value: %s" % (key, value))