Skip to content

Commit

Permalink
Merge pull request #99 from AmiyaBot/dev
Browse files Browse the repository at this point in the history
fix: 修复日志问题 #94
  • Loading branch information
vivien8261 authored Jun 27, 2024
2 parents 9ee6390 + 14efb9e commit b76c21c
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 77 deletions.
6 changes: 0 additions & 6 deletions amiyabot/adapters/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,6 @@ def text_convert(message: Message, text: str, original: str):
:return: Message 对象
"""

# <= 1.2.7
# message.text = remove_punctuation(origin)
# message.text_digits = chinese_to_digits(message.text)
# message.text_origin = origin
# message.text_initial = initial

message.text = text
message.text_digits = chinese_to_digits(message.text)
message.text_unsigned = remove_punctuation(original)
Expand Down
1 change: 0 additions & 1 deletion amiyabot/adapters/tencent/qqGroup/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import time
import requests


from ..qqGuild.api import QQGuildAPI, log


Expand Down
10 changes: 9 additions & 1 deletion amiyabot/builtin/lib/timedTask/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,15 @@


class Scheduler(AsyncIOScheduler):
options = {'executors': {'default': AsyncIOExecutor()}, 'job_defaults': {'coalesce': False, 'max_instances': 1}}
options = {
'executors': {
'default': AsyncIOExecutor(),
},
'job_defaults': {
'coalesce': False,
'max_instances': 1,
},
}

def event_listener(self, mask):
def register(task):
Expand Down
15 changes: 8 additions & 7 deletions amiyabot/handler/messageHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,17 @@


async def message_handler(bot: BotHandlerFactory, data: Union[Message, Event, EventList]):
appid = str(bot.appid)
instance = bot.instance
instance_name = str(instance)
if instance_name not in adapter_log:
adapter_log[instance_name] = LoggerManager(
name=instance_name,
save_path=os.path.join(LOG_FILE_SAVE_PATH, 'adapters'),
save_filename=instance_name,

if appid not in adapter_log:
adapter_log[appid] = LoggerManager(
name=str(instance),
save_path=os.path.join(LOG_FILE_SAVE_PATH, 'bots'),
save_filename=appid,
)

_log = adapter_log[instance_name]
_log = adapter_log[appid]

# 执行事件响应
if not isinstance(data, Message):
Expand Down
41 changes: 41 additions & 0 deletions amiyabot/log/handlers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import os
import sys
import logging

from typing import Optional
from concurrent_log_handler import ConcurrentRotatingFileHandler
from amiyabot.util import argv


LOG_FILE_SAVE_PATH = argv('log-file-save-path', str) or './log'
LOG_FILE_MAX_BYTES = argv('log-file-max-bytes', int) or (512 * 1024)
LOG_FILE_BACKUP_COUNT = argv('log-file-backup-count', int) or 10


class LogHandlers:
debug_mode = argv('debug', bool)
level = logging.DEBUG if debug_mode else logging.INFO
formatter = logging.Formatter(f'%(asctime)s [%(name)9s][%(levelname)9s]%(message)s')
stream_handler: Optional[logging.StreamHandler] = None

@classmethod
def get_stream_handler(cls):
if not cls.stream_handler:
cls.stream_handler = logging.StreamHandler(stream=sys.stdout)
cls.stream_handler.setFormatter(cls.formatter)
cls.stream_handler.setLevel(cls.level)

return cls.stream_handler

@classmethod
def get_file_handler(cls, save_path: str, save_filename: str):
file_handler = ConcurrentRotatingFileHandler(
filename=os.path.join(save_path, f'{save_filename}.log'),
encoding='utf-8',
maxBytes=LOG_FILE_MAX_BYTES,
backupCount=LOG_FILE_BACKUP_COUNT,
)
file_handler.setFormatter(cls.formatter)
file_handler.setLevel(cls.level)

return file_handler
68 changes: 8 additions & 60 deletions amiyabot/log/manager.py
Original file line number Diff line number Diff line change
@@ -1,94 +1,42 @@
import os
import sys
import logging
import traceback

from typing import Union, List, Type, Callable, Optional, Awaitable
from contextlib import asynccontextmanager, contextmanager
from concurrent_log_handler import ConcurrentRotatingFileHandler
from amiyabot.util import argv, create_dir
from amiyabot.util import create_dir

LOG_FILE_SAVE_PATH = argv('log-file-save-path', str) or './log'
LOG_FILE_MAX_BYTES = argv('log-file-max-bytes', int) or (512 * 1024)
LOG_FILE_BACKUP_COUNT = argv('log-file-backup-count', int) or 10
from .handlers import LogHandlers, LOG_FILE_SAVE_PATH


class LoggerManager:
user_logger = None

log_handlers: List[logging.Handler] = []

def __init__(
self,
name: str = '',
level: Optional[int] = None,
formatter: str = '',
save_path: str = '',
save_filename: str = 'running',
):
self.debug_mode = argv('debug', bool)

self.level = level or (logging.DEBUG if self.debug_mode else logging.INFO)

if not formatter:
n = '[%(name)9s]' if name else ''
formatter = f'%(asctime)s {n}[%(levelname)9s]%(message)s'

fmt = logging.Formatter(formatter)

self.save_path = save_path or LOG_FILE_SAVE_PATH
self.file_handler = ConcurrentRotatingFileHandler(
filename=os.path.join(self.save_path, f'{save_filename}.log'),
encoding='utf-8',
maxBytes=LOG_FILE_MAX_BYTES,
backupCount=LOG_FILE_BACKUP_COUNT,
)
self.file_handler.setFormatter(fmt)
self.file_handler.setLevel(self.level)

self.stream_handler = logging.StreamHandler(stream=sys.stdout)
self.stream_handler.setFormatter(fmt)
self.stream_handler.setLevel(self.level)
def __init__(self, name: str, save_path: str = LOG_FILE_SAVE_PATH, save_filename: str = 'running'):
self.save_path = save_path

self.__logger = logging.getLogger(name=name)
self.__logger.setLevel(self.level)
self.__logger.addHandler(self.file_handler)
self.__logger.addHandler(self.stream_handler)
self.__logger.setLevel(LogHandlers.level)
self.__logger.addHandler(LogHandlers.get_stream_handler())
self.__logger.addHandler(LogHandlers.get_file_handler(save_path, save_filename))

@classmethod
def use(cls, logger_cls):
cls.user_logger = logger_cls()

@classmethod
def add_handler(cls, handler: logging.Handler):
cls.log_handlers.append(handler)
return handler

@classmethod
def remove_handler(cls, handler: logging.Handler):
if handler in cls.log_handlers:
cls.log_handlers.remove(handler)

@property
def logger(self):
if self.user_logger and self != self.user_logger:
return self.user_logger

create_dir(self.save_path)

for h in set(self.log_handlers) - set(self.__logger.handlers):
self.__logger.addHandler(h)

for h in set(self.__logger.handlers) - set(self.log_handlers):
if h not in (self.file_handler, self.stream_handler):
self.__logger.removeHandler(h)

return self.__logger

@property
def print_method(self):
def method(text: str):
if self.debug_mode:
if LogHandlers.debug_mode:
stack = traceback.extract_stack()
source = stack[-3]
filename = os.path.basename(source.filename)
Expand Down
3 changes: 2 additions & 1 deletion pylint.conf
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,8 @@ disable=fixme,
unused-import,
keyword-arg-before-vararg,
f-string-without-interpolation,
arguments-differ
arguments-differ,
possibly-used-before-assignment

# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ setuptools~=60.2.0
starlette~=0.19.1
uvicorn~=0.18.2
websockets~=10.1
zhon~=1.1.5
zhon~=1.1.5

0 comments on commit b76c21c

Please sign in to comment.