Skip to content

Commit 371a040

Browse files
committed
improve logging system
1 parent dc15e31 commit 371a040

10 files changed

Lines changed: 44 additions & 15 deletions

File tree

comiclib/config.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
from pydantic import BaseSettings
22
from typing import Union
33
import re
4+
import logging
5+
6+
logger = logging.getLogger('ComicLib')
47

58
class Settings(BaseSettings):
69
debug: bool = False
10+
loglevel: str = 'INFO'
711
content: str = '.'
812
thumb: str = './thumb'
913
metadata: str = 'sqlite:///./comiclib_metadata.db'
@@ -16,7 +20,14 @@ class Settings(BaseSettings):
1620
settings = Settings()
1721

1822
if settings.debug:
19-
print(settings)
23+
settings.loglevel = 'DEBUG'
24+
numeric_level = getattr(logging, settings.loglevel.upper(), None)
25+
if not isinstance(numeric_level, int):
26+
raise ValueError(f'Invalid log level: {settings.loglevel}')
27+
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(name)s: %(message)s',
28+
datefmt='%Y-%m-%d %H:%M:%S',
29+
level=numeric_level)
30+
logger.debug(settings)
2031

2132
settings.UA_convert_jxl = re.compile(settings.UA_convert_jxl)
2233
settings.UA_convert_all = re.compile(settings.UA_convert_all)

comiclib/frontend_boost.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
from pathlib import Path
33
import requests
44

5+
import logging
6+
logger = logging.getLogger(__name__)
7+
58
dependencies = {
69
'@fortawesome/fontawesome-free': '6.4.0',
710
'@jcubic/tagger': '0.4.4',
@@ -73,11 +76,11 @@
7376
vendor_version = 0
7477
version_file = Path(__file__).parent / 'LANraragi/public/version'
7578
if not version_file.exists() or int(version_file.read_text()) < vendor_version:
76-
print('Installing/updating front-end files...')
79+
logger.info('Installing/updating front-end files...')
7780

7881
s = requests.session()
7982
for name in dependencies:
80-
print('downloading', name)
83+
logger.info('downloading', name)
8184
r = s.get(f"https://registry.npmjs.com/{name}/-/{name.rpartition('/')[-1]}-{dependencies[name]}.tgz", allow_redirects=True)
8285
r.raise_for_status()
8386
with tarfile.open(fileobj=io.BytesIO(r.content), mode='r:gz') as t:

comiclib/scan.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44
import hashlib
55
import time
66
from pathlib import Path
7-
from pprint import pprint
7+
from pprint import pformat
8+
9+
import logging
10+
logger = logging.getLogger(__name__)
811

912
from .database import engine, Base, Archive, Tag, Category
1013
from sqlalchemy import select
@@ -26,7 +29,7 @@
2629
scanners = [(importlib.import_module('.scanner.'+name, __package__).Scanner(), name) for name in scanner.__all__] + \
2730
[(importlib.import_module(p.stem).Scanner(), p.stem) for p in Path('.').glob('*.py')]
2831
scanners.sort(key=lambda t:t[1])
29-
print("Loaded scanners:", [scanner[1] for scanner in scanners])
32+
logger.info(f"Loaded scanners: {[scanner[1] for scanner in scanners]}")
3033

3134

3235
def scan(paths):
@@ -60,7 +63,7 @@ def scan(paths):
6063
continue
6164
if not any(tag.startswith("date_added:") for tag in metadata["tags"]):
6265
metadata["tags"].add(f"date_added:{int(real_path.stat().st_mtime)}")
63-
pprint(metadata)
66+
logging.debug(pformat(metadata))
6467
a.title = metadata["title"]
6568
a.subtitle = metadata["subtitle"]
6669
a.source = metadata["source"]
@@ -105,8 +108,7 @@ def watch():
105108
time.sleep(1)
106109
scan([fname])
107110
except Exception as err:
108-
if settings.debug:
109-
print(err)
111+
logger.error(err)
110112

111113

112114
def scannow():

comiclib/scanner/10-zip.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22

33
from zipfile import ZipFile
44

5+
import logging
6+
logger = logging.getLogger(__name__)
57

68
class Scanner:
79
'''Handle regular zip files, with the filename as the title.'''
810

911
def scan(self, path: Path, id: str, metadata: dict, prev_scanners: list[str]) -> bool:
1012
if path.match('**/*.zip') and not path.is_dir():
11-
print(f' -> zip.py get {path}')
13+
logger.info(f' <- {path}')
1214
metadata["title"] = path.stem
1315
with ZipFile(path) as z:
1416
metadata["pagecount"] = len(

comiclib/scanner/20-ccloli.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from pathlib import Path
22
from zipfile import ZipFile
33

4+
import logging
5+
logger = logging.getLogger(__name__)
46

57
try:
68
from charset_normalizer import from_bytes
@@ -24,7 +26,7 @@ def scan(self, path: Path, id: str, metadata: dict, prev_scanners: list[str]) ->
2426
info = z_comments
2527
else:
2628
return False
27-
print(f' -> ccloli get {path}')
29+
logger.info(f' <- {path}')
2830
if "hentai.org" not in info[2]: return False
2931
metadata["title"] = info[0]
3032
metadata["subtitle"] = info[1]

comiclib/scanner/21-hath.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
from pathlib import Path
22
import re
33

4+
import logging
5+
logger = logging.getLogger(__name__)
46

57
class Scanner:
68
'''For archives downloaded via Hentai@Home'''
79

810
def scan(self, path: Path, id: str, metadata: dict, prev_scanners: list[str]) -> bool:
911
if path.is_dir() and (path / 'galleryinfo.txt').exists():
10-
print(f' -> hath.py get {path}')
12+
logger.info(f' <- {path}')
1113
metadata["source"] = 'https://exhentai.org/g/' + re.search(r"\[(\d+)\]$", path.name)[1] + '/'
1214
information = (path / 'galleryinfo.txt').read_text().splitlines()
1315
_key, _, title = information[0].partition(':')

comiclib/scanner/30-importEHdb.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ class Settings(BaseSettings):
1010
importEHdb_matchtorrent: bool = True
1111
settings = Settings()
1212

13+
import logging
14+
logger = logging.getLogger(__name__)
1315

1416
def blur_title(title: str):
1517
if not isinstance(title, str):
@@ -34,7 +36,7 @@ class Scanner:
3436

3537
def __init__(self) -> None:
3638
if Path("api_dump.sqlite").exists():
37-
print('Loading ehentai metadata database, please wait...')
39+
logger.info('Loading ehentai metadata database, please wait...')
3840
self.con = sqlite3.connect("api_dump.sqlite", check_same_thread=False)
3941
if settings.importEHdb_matchtitle:
4042
self.db_title = {blur_title(row[0]): row[1] for row in self.con.execute("SELECT title, gid FROM gallery") if not row[0] is None}
@@ -47,7 +49,7 @@ def __init__(self) -> None:
4749
if torrent['name'] is None: continue
4850
self.db_title_torrent[blur_title(Path(torrent['name']).stem)] = gid
4951
self.con.row_factory = dict_factory
50-
print('Loaded.')
52+
logger.info('Loaded.')
5153
else:
5254
self.con = None
5355

@@ -72,7 +74,7 @@ def scan(self, path: Path, id: str, metadata: dict, prev_scanners: list[str]) ->
7274
if self.con is None:
7375
return False
7476
elif prev_scanners and not (gid := self.get_gid(metadata)) is None:
75-
print(f' -> importEHdb get {path}')
77+
logger.info(f' <- {path}')
7678
res = self.con.execute("SELECT title, title_jpn, category, posted, thumb, artist, `group`, parody, character, female, male, language, mixed, other, cosplayer, rest FROM gallery WHERE gid == ?", (gid,)).fetchone()
7779
if res is None: return False
7880
metadata["title"] = res.pop("title")

comiclib/scanner/40-thumb.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
from pathlib import Path
22
from ..utils import extract_thumbnail
33

4+
import logging
5+
logger = logging.getLogger(__name__)
6+
47
class Scanner:
58
'''Generate thumbnails from files.'''
69

710
def scan(self, path: Path, id: str, metadata: dict, prev_scanners: list[str]) -> bool:
811
if not prev_scanners or not metadata.get('thumb') is None:
912
return False
10-
print(f' -> thumb.py get {path}')
13+
logger.info(f' <- {path}')
1114
thumb = extract_thumbnail(path, id, 1)
1215
metadata['thumb'] = str(thumb)
1316
return True

docs/en/docs/settings.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ The following is a list of available settings:
2727
| Environment variable | Description | Default value |
2828
| ------- | ---- | ----- |
2929
| `debug` | Turn on debug output (`True`/`False`) | `False` |
30+
| `loglevel` | Log level (`DEBUG`/`INFO`/`WARNING`/`ERROR`/`CRITICAL`). If `debug` is `True`, it will be overwritten to `DEBUG` | `INFO` |
3031
| `content` | The path where the comic file is stored (due to [a problem with Python](https://github.com/python/cpython/issues/77609), following symbolic links is not currently supported) | `.` |
3132
| `thumb` | The path where the generated thumbnails are stored | `./thumb`|
3233
| `metadata` | The URL for metadata database, refer to [SQLAlchemy documentation](https://docs.sqlalchemy.org/en/20/core/engines.html#database-urls) | `sqlite:///./comiclib_metadata.db` |

docs/zh/docs/settings.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
| 环境变量 | 说明 | 默认值 |
2828
| ------- | ---- | ----- |
2929
| `debug` | 开启调试输出(`True`/`False`| `False` |
30+
| `loglevel` | 日志级别(`DEBUG`/`INFO`/`WARNING`/`ERROR`/`CRITICAL`),若`debug``True`,会被覆盖为`DEBUG` | `INFO` |
3031
| `content` | 漫画文件存放的路径(由于 [Python 的一个问题](https://github.com/python/cpython/issues/77609),暂不支持跟随符号链接) | `.` |
3132
| `thumb` | 生成的缩略图存放的路径 | `./thumb`|
3233
| `metadata` | 元数据库 URL,参考[SQLAlchemy 文档](https://docs.sqlalchemy.org/en/20/core/engines.html#database-urls) | `sqlite:///./comiclib_metadata.db` |

0 commit comments

Comments
 (0)