Skip to content

Commit

Permalink
feat: 实现日志文件轮转功能,优化日志配置和初始化流程
Browse files Browse the repository at this point in the history
  • Loading branch information
HisAtri committed Feb 25, 2025
1 parent 6a58494 commit 4cb75df
Show file tree
Hide file tree
Showing 6 changed files with 83 additions and 72 deletions.
7 changes: 4 additions & 3 deletions api/tag.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import os
import json
import logging

from . import *

from flask import request

from mod import tag
from mod.auth import require_auth_decorator
from mod.dev.debugger import debugger

logger = logging.getLogger(__name__)

@app.route('/tag', methods=['POST', 'PUT'], endpoint='set_tag_endpoint')
@app.route('/confirm', methods=['POST', 'PUT'], endpoint='set_tag_endpoint')
Expand All @@ -24,9 +25,9 @@ def set_tag():
audio_path: str = music_data.get("path")
if not audio_path:
return "Missing 'path' key in JSON.", 422
debugger.log("info", f"Editing file {audio_path}")
logger.debug(f"Editing file {audio_path}")
if not os.path.exists(audio_path):
debugger.log("error", f"File not found: {audio_path}")
logger.error(f"File not found: {audio_path}")
return "File not found.", 404
supported_tags = {
"tracktitle": {"allow": (str, bool, type(None)), "caption": "Track Title"},
Expand Down
36 changes: 28 additions & 8 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,30 @@
import logging
import sys
import os

from logging.handlers import RotatingFileHandler
from waitress import serve

# 导入其他模块前配置日志系统
logging.basicConfig(
level=logging.INFO if not 'debug' in sys.argv else logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[logging.StreamHandler()]
)

os.makedirs(os.path.join(os.path.dirname(sys.argv[0]), 'logs'), exist_ok=True)
file_handler = RotatingFileHandler(
os.path.join(os.path.dirname(sys.argv[0]), 'logs', 'log.txt'),
maxBytes=1024*1024,
backupCount=5
)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger = logging.getLogger('')
logger.addHandler(file_handler)


from mod import check_update
from mod.args import args
from mod.dev.debugger import debugger
from api import *
from api import __import__

Expand All @@ -15,10 +34,9 @@ def run_server(debug=False):
# Waitress WSGI 服务器
serve(app, host=args("server", "ip"), port=args("server", "port"), threads=32, channel_timeout=30)
else:
debugger.debug = True
debugger.log("info", "Debug模式已开启")
debugger.log("info", f"Version: {args.version}")
debugger.log("info", f"Auth: {args('auth')}")
logger.debug("Debug模式已开启")
logger.debug(f"Version: {args.version}")
logger.debug(f"Auth: {args('auth')}")
app.run(host='0.0.0.0', port=args("server", "port"), debug=True)


Expand All @@ -28,9 +46,11 @@ def run_server(debug=False):
raise RuntimeError(
"Python 3.10+ required, but you are using Python {}.{}.{}.".format(*sys.version_info[:3])
)
# 日志配置
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger('')

# 日志级别根据debug参数调整
if args.debug:
logging.getLogger('').setLevel(logging.DEBUG)

logger.info("正在启动服务器")
logger.info("您可通过爱发电支持我们,爱发电主页 https://afdian.com/a/ghacg")
check_update.run(version=args.version)
Expand Down
Empty file removed mod/dev/__init__.py
Empty file.
28 changes: 0 additions & 28 deletions mod/dev/debugger.py

This file was deleted.

16 changes: 0 additions & 16 deletions mod/log.py

This file was deleted.

68 changes: 51 additions & 17 deletions mod/tag.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import base64
import os
import io
import logging

from PIL import Image

from mod import music_tag

logger = logging.getLogger(__name__)

TAG_MAP = {
'tracktitle': '曲目标题',
'artist': '艺术家',
Expand All @@ -22,15 +25,20 @@ def dump_b64(album_art: music_tag.file.MetadataItem) -> str:
:param album_art:
:return:
"""
artwork = album_art.values[0]
img_data = artwork.data
img_format = artwork.format
img = Image.open(io.BytesIO(img_data))
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format=img_format)
# 将字节流编码为base64字符串
img_base64 = base64.b64encode(img_byte_arr.getvalue())
return img_base64.decode()
logger.debug("开始处理专辑封面图片的base64编码")
try:
artwork = album_art.values[0]
img_data = artwork.data
img_format = artwork.format
img = Image.open(io.BytesIO(img_data))
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format=img_format)
img_base64 = base64.b64encode(img_byte_arr.getvalue())
logger.debug(f"图片编码完成,格式: {img_format}")
return img_base64.decode()
except Exception as e:
logger.error(f"处理专辑封面时发生错误: {str(e)}")
raise


def write(tags: dict, file: any) -> None:
Expand All @@ -39,39 +47,65 @@ def write(tags: dict, file: any) -> None:
:param file: string, file-like object, io.StringIO, etc.
:return: None
"""
logger.info(f"开始写入音乐标签")

if not isinstance(tags, dict):
raise TypeError(f'Tags should be dict, but {type(tags).__name__} found.')
err_msg = f'Tags should be dict, but {type(tags).__name__} found.'
logger.error(err_msg)
raise TypeError(err_msg)

file_path = file if isinstance(file, str) else (file.name if hasattr(file, 'name') else None)
if not file_path or not os.path.exists(file_path):
raise FileNotFoundError(f'File {file_path} does not exist or path is invalid.')
err_msg = f'File {file_path} does not exist or path is invalid.'
logger.error(err_msg)
raise FileNotFoundError(err_msg)

logger.debug(f"准备写入文件: {file_path}")
music_file_obj = music_tag.load_file(file)

for tag_name, tag_value in tags.items():
if tag_name == "artwork" and tag_value:
logger.debug("处理专辑封面数据")
artwork_raw: bytes = base64.b64decode(tag_value)
artwork = music_tag.file.Artwork(artwork_raw)
music_file_obj[tag_name] = artwork
elif tag_name in TAG_MAP and tag_value:
logger.debug(f"写入标签 {TAG_MAP[tag_name]}: {tag_value}")
music_file_obj[tag_name] = tag_value
elif tag_value is False:
logger.debug(f"删除标签: {tag_name}")
del music_file_obj[tag_name]
else:
logger.warning(f"跳过无效的标签: {tag_name}")
continue

music_file_obj.save()
logger.debug("音乐标签写入完成")


def read(file: any) -> dict:
file_path = file if isinstance(file, str) else (file.name if hasattr(file, 'name') else None)

if not file_path or not os.path.exists(file_path):
logger.warning(f"文件不存在或路径无效: {file_path}")
return {}

logger.debug(f"开始读取音乐文件标签: {file_path}")
result = {}
for tag_name, tag_func in TAG_MAP.items():
if tag_name == "artwork":
result[tag_name] = dump_b64(music_tag.load_file(file_path).resolve(tag_name))
else:
result[tag_name] = str(music_tag.load_file(file_path).resolve(tag_name))
return result

try:
for tag_name, tag_desc in TAG_MAP.items():
logger.debug(f"读取标签 {tag_desc}")
if tag_name == "artwork":
result[tag_name] = dump_b64(music_tag.load_file(file_path).resolve(tag_name))
else:
result[tag_name] = str(music_tag.load_file(file_path).resolve(tag_name))

logger.debug("音乐标签读取完成")
return result
except Exception as e:
logger.error(f"读取标签时发生错误: {str(e)}")
raise


if __name__ == '__main__':
Expand Down

0 comments on commit 4cb75df

Please sign in to comment.