Add separate module for handling logs

This commit is contained in:
James Wang 2015-12-26 20:21:15 -05:00
parent 1e911c3f20
commit e13a789f15
5 changed files with 47 additions and 4 deletions

1
.gitignore vendored
View file

@ -1,6 +1,7 @@
.vagrant
.secret_key
.bundle/config
logs/
# Object files
*.o

View file

@ -1,4 +1,5 @@
import admin
import logger
import models
import user
import utils

41
server/api/logger.py Normal file
View file

@ -0,0 +1,41 @@
import datetime
import logging
import logging.handlers
import os
NOTSET = 0
DEBUG = 10
INFO = 20
WARNING = 30
ERROR = 40
CRITICAL = 50
def initialize_logs():
registration_logger = logging.getLogger("registrations")
login_logger = logging.getLogger("logins")
submission_logger = logging.getLogger("submissions")
registration_logger.setLevel(logging.INFO)
login_logger.setLevel(logging.INFO)
submission_logger.setLevel(logging.INFO)
base = os.path.dirname(__file__).strip("api")
log_path = os.path.join(base, "logs")
if not os.path.exists(log_path):
os.mkdir(log_path)
logs = [os.path.join(log_path, "registrations.log"), os.path.join(log_path, "logins.log"), os.path.join(log_path, "submissions.log")]
registration_log = logging.handlers.RotatingFileHandler(logs[0], maxBytes=10000)
login_log = logging.handlers.RotatingFileHandler(logs[1], maxBytes=10000)
submission_log = logging.handlers.RotatingFileHandler(logs[2], maxBytes=10000)
registration_logger.addHandler(registration_log)
login_logger.addHandler(login_log)
submission_logger.addHandler(submission_log)
def log(log, level, message):
logger = logging.getLogger(log)
message = "[%s] %s" % (datetime.datetime.now().strftime("%m/%d/%Y %X"), message)
logger.log(level, message)

View file

@ -4,7 +4,7 @@ from flask import current_app as app
from models import db, Users
from decorators import api_wrapper
import logging
import logger
import requests
import utils
@ -39,8 +39,7 @@ def user_register():
return { "success": 0, "message": "Email has already been used." }
add_user(name, username, email, password)
logger = logging.getLogger("regs")
logger.warn("[{0}] {1} registered with {2}".format(time.strftime("%m/%d/%Y %X"), name.encode("utf-8"), email.encode("utf-8")))
logger.log("registrations", logger.INFO, "%s registered with %s" % (name.encode("utf-8"), email.encode("utf-8")))
return { "success": 1, "message": "Success!" }

View file

@ -1,9 +1,9 @@
from argparse import ArgumentParser
from flask import Flask
import api
import config
import json
import api
app = Flask(__name__)
@ -18,6 +18,7 @@ app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = config.SQLALCHEMY_TRACK_MODIFICAT
app.register_blueprint(api.admin.blueprint, url_prefix="/api/admin")
app.register_blueprint(api.user.blueprint, url_prefix="/api/user")
api.logger.initialize_logs()
@app.route("/api")
def api_main():