Skip to content

Commit

Permalink
add logger
Browse files Browse the repository at this point in the history
  • Loading branch information
LarryKwon committed Sep 1, 2024
1 parent 8deb988 commit 22542bf
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 19 deletions.
55 changes: 52 additions & 3 deletions logs/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,6 @@ def format(self, record):
return json.dumps(
OrderedDict(
[
("id", str(uuid.uuid4())),
("level", record.levelname),
("time", datetime.fromtimestamp(record.created).isoformat()),
*message.items(),
]
), ensure_ascii=False
Expand Down Expand Up @@ -92,6 +89,58 @@ def shouldRollover(self, record) -> int:
return 1
return 0


def doRollover(self):
"""
do a rollover; in this case, a date/time stamp is appended to the filename
when the rollover happens. However, you want the file to be named for the
start of the interval, not the current time. If there is a backup count,
then we have to get a list of matching filenames, sort them and remove
the one with the oldest suffix.
"""
if self.stream:
self.stream.close()
self.stream = None
# get the time that this sequence started at and make it a TimeTuple
currentTime = int(time.time())
dstNow = time.localtime(currentTime)[-1]
t = self.rolloverAt - self.interval
self.baseFilename = os.path.abspath(os.fspath(os.path.join('/var/www/otlplus/logs/', f'response-{datetime.now().strftime("%Y-%m-%d")}.log')))
if self.utc:
timeTuple = time.gmtime(t)
else:
timeTuple = time.localtime(t)
dstThen = timeTuple[-1]
if dstNow != dstThen:
if dstNow:
addend = 3600
else:
addend = -3600
timeTuple = time.localtime(t + addend)
dfn = self.rotation_filename(self.baseFilename + "." +
time.strftime(self.suffix, timeTuple))
if os.path.exists(dfn):
os.remove(dfn)
self.rotate(self.baseFilename, dfn)
if self.backupCount > 0:
for s in self.getFilesToDelete():
os.remove(s)
if not self.delay:
self.stream = self._open()
newRolloverAt = self.computeRollover(currentTime)
while newRolloverAt <= currentTime:
newRolloverAt = newRolloverAt + self.interval
#If DST changes and midnight or weekly rollover, adjust for this.
if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
dstAtRollover = time.localtime(newRolloverAt)[-1]
if dstNow != dstAtRollover:
if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
addend = -3600
else: # DST bows out before next rollover, so we need to add an hour
addend = 3600
newRolloverAt += addend
self.rolloverAt = newRolloverAt

def exitRollover(self):
self.delay = True
if self.stream:
Expand Down
21 changes: 11 additions & 10 deletions logs/log_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@ def __init__(self, request):
def format_request(self) -> dict:
result = {
"method": self.request.method,
"meta": {
key.lower(): str(value)
for key, value in self.request.META.items()
if key in REQUEST_META_KEYS
},
"UUID": self.request.META['HTTP_UUID'],
# "meta": {
# key.lower(): str(value)
# for key, value in self.request.META.items()
# if key in REQUEST_META_KEYS
# },
"UUID": self.request.META['HTTP_UUID'] if hasattr(self.request.META,'HTTP_UUID') else None,
"path": self.request.path_info,
}

Expand All @@ -45,7 +45,7 @@ def format_request(self) -> dict:
result["data"] = self.request.POST.dict()

try:
result["user"] = self.request.user.id
result["user"] = self.request.user.username
except AttributeError:
result["user"] = None

Expand All @@ -66,14 +66,15 @@ def __init__(self, request, response):
def format(self) -> dict:
return {
"request": self.format_request(),
"response": self.format_response()
"response": self.format_response(),
"duration": self.duration
}

def format_response(self) -> dict:
result = {
"status": self.response.status_code,
"headers": dict(self.response.items()),
"charset": getattr(self.response, "charset", 'utf-8'),
# "headers": dict(self.response.items()),
# "charset": getattr(self.response, "charset", 'utf-8'),
}

try:
Expand Down
12 changes: 10 additions & 2 deletions logs/middleware.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from datetime import timedelta
import time

from . import log
from .handler import ConsoleHandler
from .log_object import ErrorLogObject, LogObject
Expand All @@ -8,13 +11,18 @@ def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
start = time.monotonic()
response = self.get_response(request)
end = time.monotonic()
duration = (end - start) * 1000 # 밀리초 단위로 변환
log_data = LogObject(request, response)
log_data.duration = duration
if response.status_code == 500:
return response
if 400 <= response.status_code < 500:
log.warning(LogObject(request, response))
log.warning(log_data)
else:
log.info(LogObject(request, response))
log.info(log_data)
return response

@staticmethod
Expand Down
6 changes: 6 additions & 0 deletions logs/response.log.2024-08-26

Large diffs are not rendered by default.

12 changes: 8 additions & 4 deletions otlplus/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from datetime import datetime

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

Expand Down Expand Up @@ -117,7 +118,7 @@
import os
import sys

LOG_FILE_PATH = os.environ.get("LOG_FILE_PATH", "/var/www/otlplus/logs/response.log")
LOG_FILE_PATH = os.environ.get("LOG_FILE_PATH", "/var/www/otlplus/logs/")
LOG_MAX_BYTES = int(os.environ.get("LOG_MAX_BYTES", 1024 * 1024 * 10))
LOG_BACKUP_COUNT = int(os.environ.get("LOG_BACKUP_COUNT", 100))

Expand All @@ -142,7 +143,7 @@
"rotating_file": {
"level": "INFO",
"class": "logs.handler.SizedTimedRotatingFileHandler",
"filename": LOG_FILE_PATH,
"filename": os.path.join('/var/www/otlplus/logs/', f'response-{datetime.now().strftime("%Y-%m-%d")}.log'),
"max_bytes": LOG_MAX_BYTES,
"backup_count": LOG_BACKUP_COUNT,
"encoding": "utf-8",
Expand Down Expand Up @@ -203,8 +204,11 @@ def ugettext(s):

with open(os.path.join(BASE_DIR, "keys/sso_secret")) as f:
SSO_SECRET_KEY = f.read().strip()
SSO_CLIENT_ID = os.getenv("SSO_CLIENT_ID")
SSO_IS_BETA = DEBUG
# SSO_CLIENT_ID = os.getenv("SSO_CLIENT_ID")
SSO_CLIENT_ID = "testbecb93acf2c87d2e064c" # SSO의 'Name' (또는 'Client ID') 필드
SSO_SECRET_KEY = "74166705c80967e09c80" # SSO의 'Secret Key' 필드

SSO_IS_BETA = False

LOGIN_URL = "/session/login/"
LOGOUT_URL = "/session/logout/"
Expand Down

0 comments on commit 22542bf

Please sign in to comment.