Skip to content

Commit

Permalink
Add an exponential backoff to sending logs
Browse files Browse the repository at this point in the history
Closes #3
  • Loading branch information
webknjaz committed Nov 11, 2018
1 parent 0cca75f commit 5c16c02
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions opencanary/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@
import base64
import time
import dateutil.parser
import random
import re

from datetime import datetime
from logging.handlers import SocketHandler

from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from twisted.internet.task import deferLater
import treq

import six
Expand Down Expand Up @@ -337,11 +339,27 @@ def __init__(self, server_url, client_id, secret):

@inlineCallbacks
def _send_record_over_http(self, record):
yield treq.post(
self._log_server_url,
data=record.message,
headers=self._http_headers,
)
failures_counter = 0
base_num = 2
cap_sleep = 300
while True:
try:
yield treq.post(
self._log_server_url,
data=record.message,
headers=self._http_headers,
)
return
except twisted.web.error.Error:
failures_counter += 1
timeout = random.triangular(
0,
min(
cap_sleep,
base_num ** failures_counter + random.random(),
)
)
yield deferLater(reactor, timeout, lambda: None) # sleep

def emit(self, record):
reactor.callLater(0, self._send_record_over_http, record)

0 comments on commit 5c16c02

Please sign in to comment.