tornado 异步日志统计获取IP地址和对应城市
Posted 74 months ago ip city tornado log
ip转城市
直接贴代码
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class SearchIp(metaclass=Singleton):
def __init__(self):
try:
dbpath = os.path.abspath("./utils/ip/ip2region.db")
self.search = Ip2Region(dbpath)
except IOError:
log.error("err connect db",IOError.errno)
else:
log.info("db connect success")
def getSession(self):
return self.search
def searchCity(self,ip):
try:
if self.getSession().isip(ip):
city = self.getSession().btreeSearch(ip=ip).get("region","火星").decode("utf-8")
else:
city = "火星"
except IOError:
log.error(IOError)
city = "火星"
return city
else:
return city
def close(self):
self.search.close()
单例模式 然后ip转城市
异步存到mongodb
class baseHttp (tornado.web.RequestHandler):
executor = ThreadPoolExecutor(100)
@tornado.web.asynchronous
@tornado.gen.coroutine
def initialize(self):
yield self.logsave()
@run_on_executor
def logsave(self):
ipDao.saveLog(self.request.remote_ip,self.request.uri,self.request.headers.get("User-Agent","鬼知道"))
似乎还凑活~~