mirror of
https://github.com/wlinator/luminara.git
synced 2024-10-02 18:03:12 +00:00
Logger now updates two files
This commit is contained in:
parent
6b6bfae516
commit
c951fda694
3 changed files with 104 additions and 42 deletions
|
@ -1,10 +1,14 @@
|
|||
import json
|
||||
import logging
|
||||
|
||||
racu_logs = logging.getLogger('Racu.Core')
|
||||
|
||||
|
||||
def load_strings(path="config/strings.en-US.json"):
|
||||
with open(path, 'r') as file:
|
||||
data = json.load(file)
|
||||
|
||||
racu_logs.debug(f"{path} was loaded.")
|
||||
return data
|
||||
|
||||
|
||||
|
@ -12,6 +16,7 @@ def load_economy_config(path="config/economy.json"):
|
|||
with open(path, 'r') as file:
|
||||
data = json.load(file)
|
||||
|
||||
racu_logs.debug(f"{path} was loaded.")
|
||||
return data
|
||||
|
||||
|
||||
|
@ -19,4 +24,5 @@ def load_reactions(path="config/reactions.json"):
|
|||
with open(path, 'r') as file:
|
||||
data = json.load(file)
|
||||
|
||||
racu_logs.debug(f"{path} was loaded.")
|
||||
return data
|
||||
|
|
|
@ -25,6 +25,7 @@ def execute_query(query, values=None):
|
|||
cursor.execute(query)
|
||||
|
||||
conn.commit()
|
||||
racu_logs.debug(f"database.execute_query: 'query': {query}, 'values': {values}")
|
||||
return cursor
|
||||
|
||||
|
||||
|
@ -32,6 +33,8 @@ def select_query(query, values=None):
|
|||
conn = create_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
racu_logs.debug(f"database.select_query: 'query': {query}, 'values': {values}")
|
||||
|
||||
if values:
|
||||
return cursor.execute(query, values).fetchall()
|
||||
else:
|
||||
|
@ -42,6 +45,8 @@ def select_query_one(query, values=None):
|
|||
conn = create_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
racu_logs.debug(f"database.select_query_one: 'query': {query}, 'values': {values}")
|
||||
|
||||
if values:
|
||||
output = cursor.execute(query, values).fetchone()
|
||||
else:
|
||||
|
|
135
main.py
135
main.py
|
@ -9,6 +9,7 @@ SPECIAL_BALANCE_NAME=
|
|||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
import discord
|
||||
|
@ -22,15 +23,30 @@ from data.Item import Item
|
|||
from handlers.ReactionHandler import ReactionHandler
|
||||
from handlers.XPHandler import XPHandler
|
||||
|
||||
sbbot = discord.Bot(
|
||||
owner_id=os.getenv('OWNER_ID'),
|
||||
intents=discord.Intents.all(),
|
||||
activity=discord.Game(f"v{sb_tools.resources.__version__}"),
|
||||
status=discord.Status.do_not_disturb
|
||||
)
|
||||
|
||||
|
||||
class RacuFormatter(logging.Formatter):
|
||||
def converter(self, timestamp):
|
||||
tz = pytz.timezone('US/Eastern')
|
||||
converted_time = datetime.fromtimestamp(timestamp, tz)
|
||||
return converted_time
|
||||
def __init__(self, fmt=None, datefmt=None):
|
||||
super().__init__(fmt, datefmt)
|
||||
self.timezone = pytz.timezone('US/Eastern')
|
||||
|
||||
def format(self, record):
|
||||
message = record.getMessage()
|
||||
message = re.sub(r'\n', '', message) # Remove newlines
|
||||
message = re.sub(r'\s+', ' ', message) # Remove multiple spaces
|
||||
message = message.strip() # Remove leading and trailing spaces
|
||||
|
||||
record.msg = message
|
||||
return super().format(record)
|
||||
|
||||
def formatTime(self, record, datefmt=None):
|
||||
timestamp = self.converter(record.created)
|
||||
timestamp = self.timezone.localize(datetime.fromtimestamp(record.created))
|
||||
if datefmt:
|
||||
return timestamp.strftime(datefmt)
|
||||
else:
|
||||
|
@ -38,6 +54,17 @@ class RacuFormatter(logging.Formatter):
|
|||
|
||||
|
||||
def setup_logger():
|
||||
# Create a "logs" subfolder if it doesn't exist
|
||||
logs_folder = 'logs'
|
||||
if not os.path.exists(logs_folder):
|
||||
os.makedirs(logs_folder)
|
||||
|
||||
# Generate the log file path for debug-level logs
|
||||
debug_log_file = os.path.join(logs_folder, 'debug.log')
|
||||
|
||||
# Generate the log file path for info-level logs
|
||||
info_log_file = os.path.join(logs_folder, 'info.log')
|
||||
|
||||
# Initialize the logger
|
||||
logger = logging.getLogger('Racu.Core')
|
||||
if logger.handlers:
|
||||
|
@ -48,58 +75,41 @@ def setup_logger():
|
|||
|
||||
# Create console handler and set level and formatter
|
||||
console_handler = logging.StreamHandler()
|
||||
console_handler.setLevel(logging.DEBUG)
|
||||
console_handler.setLevel(logging.INFO)
|
||||
console_formatter = RacuFormatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S')
|
||||
console_handler.setFormatter(console_formatter)
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
# Create file handler and set level and formatter
|
||||
file_handler = logging.FileHandler('racu.log')
|
||||
file_handler.setLevel(logging.DEBUG)
|
||||
file_formatter = RacuFormatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S')
|
||||
file_handler.setFormatter(file_formatter)
|
||||
logger.addHandler(file_handler)
|
||||
# Create debug file handler and set level and formatter
|
||||
debug_file_handler = logging.FileHandler(debug_log_file)
|
||||
debug_file_handler.setLevel(logging.DEBUG)
|
||||
debug_file_formatter = RacuFormatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S')
|
||||
debug_file_handler.setFormatter(debug_file_formatter)
|
||||
logger.addHandler(debug_file_handler)
|
||||
|
||||
# Create info file handler and set level and formatter
|
||||
info_file_handler = logging.FileHandler(info_log_file)
|
||||
info_file_handler.setLevel(logging.INFO)
|
||||
info_file_formatter = RacuFormatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S')
|
||||
info_file_handler.setFormatter(info_file_formatter)
|
||||
logger.addHandler(info_file_handler)
|
||||
|
||||
logger.propagate = False
|
||||
return logger
|
||||
|
||||
|
||||
racu_logs = setup_logger()
|
||||
load_dotenv('.env')
|
||||
|
||||
# load all json
|
||||
strings = json_loader.load_strings()
|
||||
economy_config = json_loader.load_economy_config()
|
||||
reactions = json_loader.load_reactions()
|
||||
|
||||
sbbot = discord.Bot(
|
||||
owner_id=os.getenv('OWNER_ID'),
|
||||
intents=discord.Intents.all(),
|
||||
activity=discord.Game(f"v{sb_tools.resources.__version__}"),
|
||||
status=discord.Status.do_not_disturb
|
||||
)
|
||||
|
||||
|
||||
def load_cogs(reload=False):
|
||||
for filename in os.listdir('./modules'):
|
||||
if filename.endswith('.py'):
|
||||
if not reload:
|
||||
sbbot.load_extension(f'modules.{filename[:-3]}')
|
||||
else:
|
||||
sbbot.reload_extension(f'modules.{filename[:-3]}')
|
||||
racu_logs.info(f"Module {filename} loaded.")
|
||||
|
||||
|
||||
@sbbot.event
|
||||
async def on_ready():
|
||||
# wait until the bot is ready
|
||||
# then sync the sqlite3 database
|
||||
db.tables.sync_database()
|
||||
Item.insert_items()
|
||||
# db.tables.sync_database()
|
||||
# Item.insert_items()
|
||||
|
||||
# reload all cogs to sync db parameters
|
||||
load_cogs(reload=True)
|
||||
# load_cogs(reload=True)
|
||||
racu_logs.info("RACU IS BOOTED/READY")
|
||||
|
||||
"""
|
||||
|
@ -149,5 +159,46 @@ async def on_member_join(member):
|
|||
await guild.get_channel(welcome_channel_id).send(embed=embed, content=member.mention)
|
||||
|
||||
|
||||
racu_logs = setup_logger()
|
||||
|
||||
# load all json
|
||||
strings = json_loader.load_strings()
|
||||
economy_config = json_loader.load_economy_config()
|
||||
reactions = json_loader.load_reactions()
|
||||
|
||||
# Keep track of loaded module filenames
|
||||
loaded_modules = set()
|
||||
|
||||
|
||||
def load_cogs():
|
||||
for filename in os.listdir('./modules'):
|
||||
if filename.endswith('.py'):
|
||||
module_name = f'modules.{filename[:-3]}'
|
||||
|
||||
# if module_name in sys.modules:
|
||||
# continue # Module is already loaded
|
||||
|
||||
try:
|
||||
sbbot.load_extension(module_name)
|
||||
loaded_modules.add(filename)
|
||||
racu_logs.info(f"Module {filename} loaded.")
|
||||
|
||||
except Exception as e:
|
||||
racu_logs.error(f"Failed to load module {filename}: {e}")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
"""
|
||||
This code is only ran when main.py is the primary module,
|
||||
thus NOT when main is imported from a cog. (sys.modules)
|
||||
"""
|
||||
|
||||
racu_logs.info("RACU IS BOOTING")
|
||||
load_dotenv('.env')
|
||||
|
||||
# load db
|
||||
db.tables.sync_database()
|
||||
Item.insert_items()
|
||||
|
||||
load_cogs()
|
||||
sbbot.run(os.getenv('TOKEN'))
|
||||
|
|
Loading…
Reference in a new issue