file_table_reader/utils/logger_config.py
2026-02-24 08:47:34 +07:00

66 lines
1.7 KiB
Python
Executable File

import logging
import os
import json
from sqlalchemy import text
from database.connection import engine
LOG_DIR = "logs"
os.makedirs(LOG_DIR, exist_ok=True)
def setup_logger(name: str):
"""
Konfigurasi logger standar untuk seluruh service.
Format log:
[LEVEL] [Nama Modul] Pesan
"""
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
# Handler untuk menulis ke file
file_handler = logging.FileHandler(os.path.join(LOG_DIR, "app.log"))
file_handler.setLevel(logging.INFO)
# Handler untuk console (stdout)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
formatter = logging.Formatter('[%(levelname)s] [%(name)s] %(message)s')
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
if not logger.handlers:
logger.addHandler(file_handler)
logger.addHandler(console_handler)
return logger
async def log_activity(user_id, action_type, action_title, details=None):
payload = {
"user_id": user_id,
"action_type": action_type,
"action_title": action_title,
"action_details": json.dumps(details) if details else None
}
async with engine.begin() as conn:
await conn.execute(
text("""
INSERT INTO backend.system_logs (
user_id,
action_type,
action_title,
action_details
) VALUES (
:user_id,
:action_type,
:action_title,
:action_details
)
"""),
payload
)