Skip to content

Commit

Permalink
feat: add logging and new page after submit (#181)
Browse files Browse the repository at this point in the history
  • Loading branch information
MagneticNeedle authored Jun 15, 2023
2 parents 508f05e + 8f9dd4e commit 4728ba5
Show file tree
Hide file tree
Showing 9 changed files with 187 additions and 29 deletions.
43 changes: 43 additions & 0 deletions bfportal/bfportal/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
import os
import platform

from loguricorn.intercept import InterceptHandler

PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(PROJECT_DIR)

Expand Down Expand Up @@ -258,3 +260,44 @@
"alt",
"class",
]

LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"intercept": {
"()": InterceptHandler,
"level": 0,
},
},
"root": {
"handlers": ["intercept"],
"level": "INFO",
"propagate": False,
},
"loggers": {
"django": {
"handlers": ["intercept"],
"level": "INFO",
"propagate": False,
},
},
}

LOGGING_FORMAT = (
"<fg #26FFDF><bg #011C26>[bfportal]</></> "
"<green>[{time:DD/MM/YY HH:mm:ss}]</green> <d>[{name}:{function}:{line}]</d> "
"<level>[{level}] {message}</level>"
)


def setup_logging():
"""Setup logging for the entire project."""
import sys

from loguru import logger

logger.remove()
logger.add(
sys.stdout, colorize=True, level="INFO", backtrace=True, format=LOGGING_FORMAT
)
30 changes: 27 additions & 3 deletions bfportal/bfportal/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,33 @@
"""

import os
import warnings

from django.core.wsgi import get_wsgi_application
from loguru import logger

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bfportal.settings.production")

application = get_wsgi_application()
def init_project():
"""Initialize the project"""
logger.info("project loaded")


def init_wsgi():
"""Initialize the WSGI
Used to load .env file and set project specific settings
"""
global application
with warnings.catch_warnings():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bfportal.settings.production")
from django.core.wsgi import get_wsgi_application
from wagtail.utils.deprecation import RemovedInWagtail50Warning

warnings.filterwarnings(
"ignore", category=RemovedInWagtail50Warning
) # supress only wagtail warnings
application = get_wsgi_application()


application = None
init_project()
init_wsgi()
24 changes: 24 additions & 0 deletions bfportal/core/migrations/0080_alter_experiencepagetag_tag.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Django 4.1.7 on 2023-04-21 19:26

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("taggit", "0005_auto_20220424_2025"),
("core", "0079_remove_experiencepage_likes"),
]

operations = [
migrations.AlterField(
model_name="experiencepagetag",
name="tag",
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="%(app_label)s_%(class)s_items",
to="taggit.tag",
),
),
]
6 changes: 5 additions & 1 deletion bfportal/core/models/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,11 @@ def create_user_profile(sender, instance: User, created, **kwargs):
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
"""Called when a user data is updated"""
instance.profile.save()
if (
profile := getattr(instance, "profile", None)
) is None: # is case a user with no profile tries to log in.
profile = Profile.objects.create(user=instance)
profile.save()


class ProfilePage(RoutablePageMixin, CustomBasePage):
Expand Down
30 changes: 21 additions & 9 deletions bfportal/core/templates/core/after_submit.html
Original file line number Diff line number Diff line change
@@ -1,25 +1,37 @@
{% extends "base.html" %}
{% load i18n %}

{% block title %}{% trans "successful" %}{% endblock %}
{% block title %}
{{ exp_name | title | truncatechars:20 }}
{% if after_edit %}
Saved
{% else %}
Submitted
{% endif %}

{% endblock %}

{% block content %}
<div class="absolute table text-white h-[90%] w-full left-0 top-0">
<div class="absolute table text-white h-[90%] w-full left-0 top-0 select-none">
<div class="table-cell align-middle">
<div class="flex flex-col text-center mx-auto gap-y-4 w-max bg-card-bg p-4 rounded-xl divider divide-y divide-bf2042-3 drop-shadow-hover-bg-light-lg transition hover:drop-shadow-bf2042-3-lg duration-300 ease-in-out">
<div class="text-xl pt-4">
<div class="flex flex-col items-center mx-auto gap-y-6 w-max bg-card-bg p-4 rounded-xl">
<div class="text-xl pt-4 flex flex-col items-center gap-y-4">
<span class="text-5xl text-white font-bold"> {{ exp_name | title }} </span>
{% if after_edit %}
{{ exp_name }} {% trans "'s Changes submitted for moderation" %}
<span class="text-sm text-bf2042-4 font-medium">Your <span class="text-bf2042-6">edits</span> have been saved and sent to moderation for approval</span>
{% else %}
{{ exp_name }} {% trans "Submited Successfully for moderation" %}
<span class="text-sm text-bf2042-4 font-medium">Your experience has been successfully sent to moderation and is waiting for approval</span>
{% endif %}

</div>
<div class="">
<div class="flex flex-row gap-x-4">
<a href="/">
<button class="mt-4 p-4 bg-hover-bg-light rounded-xl hover:drop-shadow-bf2042-2 transition duration-100 ease-in-out" type="submit">{% trans 'Back To Home' %}</button>
<button class="px-4 py-2 rounded-lg bg-white text-bf2042-1 text-lg font-bold" type="submit">{% trans 'Back To Home' %}</button>
</a>
<a href="/submit">
<button class="px-4 py-2 rounded-lg bg-bf2042-4 text-bf2042-1 text-lg font-bold" type="submit">{% trans 'Submit another' %}</button>
</a>
</div>
<p>Join our <a class="text-bf2042-4 font-bold" href="https://discord.bfportal.gg/" target="_blank">Discord</a> for more</p>
</div>
</div>
</div>
Expand Down
4 changes: 2 additions & 2 deletions bfportal/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ services:
bfportal_gg_production:
image: docker.pkg.github.com/battlefield-portal-community/bfportal.gg/main:latest
restart: always
command: bash -c "python manage.py migrate --noinput && python manage.py ensure_superuser --username bfportal --email [email protected] --password '${SU_PASSWD}' && python manage.py ensure_initialization && gunicorn bfportal.wsgi:application --workers 4 --bind 0.0.0.0:${PRODUCTION_PORT}"
command: bash -c "python manage.py migrate --noinput && python manage.py ensure_superuser --username bfportal --email [email protected] --password '${SU_PASSWD}' && python manage.py ensure_initialization && gunicorn --workers 4 --bind 0.0.0.0:${PRODUCTION_PORT}"
user: "33:33"
ports:
- "${PRODUCTION_PORT}:${PRODUCTION_PORT}"
Expand Down Expand Up @@ -75,7 +75,7 @@ services:
bfportal_gg_dev:
image: docker.pkg.github.com/battlefield-portal-community/bfportal.gg/dev:latest
restart: always
command: bash -c "python manage.py migrate --noinput && python manage.py ensure_superuser --username bfportal --email [email protected] --password '${SU_PASSWD}' && python manage.py ensure_initialization && gunicorn bfportal.wsgi:application --workers 4 --bind 0.0.0.0:${DEVEL_PORT}"
command: bash -c "python manage.py migrate --noinput && python manage.py ensure_superuser --username bfportal --email [email protected] --password '${SU_PASSWD}' && python manage.py ensure_initialization && gunicorn --workers 4 --bind 0.0.0.0:${DEVEL_PORT}"
user: "33:33"
ports:
- "${DEVEL_PORT}:${DEVEL_PORT}"
Expand Down
50 changes: 50 additions & 0 deletions bfportal/gunicorn.conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from dotenv import load_dotenv

load_dotenv()

from bfportal.settings.base import setup_logging # noqa: E402

setup_logging()

logger_class = "loguricorn.Logger"

bind = "127.0.0.1:8000"
reload = False
timeout = 30
errorlog = "-"
loglevel = "info"
wsgi_app = "bfportal.wsgi:application"
capture_output = True


def when_ready(server):
"""Called just after the master process is initialized."""
server.log.info("Server is ready. Spawning workers")


def worker_int(worker):
"""Called when a worker receives the INT or QUIT signal."""
worker.log.info("worker received INT or QUIT signal")

# get traceback info
import sys
import threading
import traceback

id2name = {th.ident: th.name for th in threading.enumerate()}
code = []
for threadId, stack in sys._current_frames().items():
code.append("\n# Thread: %s(%d)" % (id2name.get(threadId, ""), threadId))
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
worker.log.debug("\n".join(code))


def worker_abort(worker):
"""Called when a worker receives the SIGABRT signal."""
worker.log.info("worker received SIGABRT signal")


print("Gunicorn config loaded")
28 changes: 14 additions & 14 deletions bfportal/manage.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
#!/usr/bin/env python
import os
import sys
import warnings

from loguru import logger
from dotenv import load_dotenv

load_dotenv()

from bfportal.settings.base import setup_logging # noqa: E402

setup_logging()

if __name__ == "__main__":
logger.remove()
logger.add(
sys.stdout,
colorize=True,
format="[ <lr>bfportal</> ]"
"[<b><fg #3b3b3b>{level: ^8}</></>]"
"[{name}.{function}:{line}]"
"[ {message} ]",
level="DEBUG",
)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bfportal.settings.dev")
with warnings.catch_warnings():
from wagtail.utils.deprecation import RemovedInWagtail50Warning

from django.core.management import execute_from_command_line
warnings.filterwarnings("ignore", category=RemovedInWagtail50Warning)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bfportal.settings.dev")
from django.core.management import execute_from_command_line

execute_from_command_line(sys.argv)
execute_from_command_line(sys.argv)
1 change: 1 addition & 0 deletions bfportal/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ isort==5.12.0
Jinja2==3.1.2
jinja2-time==0.2.0
l18n==2021.3
loguricorn==0.1.0
loguru==0.6.0
Markdown==3.4.1
MarkupSafe==2.1.2
Expand Down

0 comments on commit 4728ba5

Please sign in to comment.