Skip to content

Instantly share code, notes, and snippets.

@daTokenizer
Last active January 25, 2016 13:42
Show Gist options
  • Save daTokenizer/1b4a26da300c8b66f38b to your computer and use it in GitHub Desktop.
Save daTokenizer/1b4a26da300c8b66f38b to your computer and use it in GitHub Desktop.
from elasticsearch import Elasticsearch
import json
from datetime import datetime
class ElasticsearchLogger(object):
def __init__(self, index_name='my_index',elasticsearch_host='my_es_host'):
#connect to our cluster
self._es = Elasticsearch([{'host': elasticsearch_host, 'port': 9200}])
self._index_name = index_name
def index(self, log_type, log_data):
self._es.index(index=self._index_name, doc_type=log_type, body=log_data)
def log(self, message, log_type="event",extra=None):
if extra:
if type(extra) is dict:
extra["message"] = message
extra["timestamp"] = datetime.utcnow()
self.index(log_type,extra)
else:
extra = {
"message":message,
"timestamp": datetime.utcnow()
}
self.index(log_type,extra)
from elastic_search_logger import ElasticsearchLogger
class User(object):
def __init__(self, username):
self._user = username
self._logger = ElasticsearchLogger()
def log(self, msg=None, **kwargs):
kwargs["user"] = self._user
if not msg:
msg = kwargs["action"]
self._logger.log(msg, extra=kwargs)
if __name__ == "__main__":
import random
possible_actions = ['run', 'jump', 'shout', 'compile kernel']
possible_users = [User("Avner"),User("Balinda"),User("Chanook")]
#Who
user = random.choice(possible_users)
#what
action = random.choice(possible_actions)
#where
lat = 31.85 + (random.random()/10)
lon = 34.74 + (random.random()/10)
user.log(msg="I did somthing", action=action, location=str(lat)+ "," + str(lon))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment