Skip to content

Commit

Permalink
Merge pull request #663 from glensc/logging-rich
Browse files Browse the repository at this point in the history
  • Loading branch information
glensc committed Apr 4, 2022
2 parents cecef1b + 2c93b05 commit d0ab386
Show file tree
Hide file tree
Showing 10 changed files with 53 additions and 24 deletions.
2 changes: 1 addition & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ python-git-info = "==0.7.1"
requests = ">=2.25.1"
requests-cache = "==0.9.1"
rich = "==12.0.1"
tqdm = "==4.63.1"
tqdm = "==4.64.0"
trakt = "==3.4.0"
urllib3 = ">=1.26.6"
websocket-client = "==1.3.2"
Expand Down
8 changes: 4 additions & 4 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 6 additions & 7 deletions plextraktsync/commands/inspect.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
from urllib.parse import parse_qs, urlparse
from urllib.parse import parse_qs, quote_plus, urlparse

from plextraktsync.console import print
from plextraktsync.factory import factory
from plextraktsync.version import version


def print_watched_shows():
from rich.table import Table

from plextraktsync.console import console

trakt = factory.trakt_api()

table = Table(
Expand All @@ -22,7 +21,7 @@ def print_watched_shows():
slug = f"[link=https://trakt.tv/shows/{progress.slug}]{progress.slug}[/]"
table.add_row(id, slug, str(len(progress.seasons)))

console.print(table)
print(table)


def inspect_media(id):
Expand All @@ -41,7 +40,7 @@ def inspect_media(id):
print(f"URL: {url}")

media = pm.item
print(f"Media.Type: {media.type}")
print(f"Media.Type: '{media.type}'")
print(f"Media.Guid: '{media.guid}'")
if not pm.is_legacy_agent:
print(f"Media.Guids: {media.guids}")
Expand All @@ -55,11 +54,11 @@ def inspect_media(id):

print("Parts:")
for index, part in enumerate(pm.parts, start=1):
print(f" Part {index}: {part.file}")
print(f" Part {index}: [link=file://{quote_plus(part.file)}]{part.file}[/link]")

print("Guids:")
for guid in pm.guids:
print(f" Guid: {guid}, Id: {guid.id}, Provider: {guid.provider}")
print(f" Guid: {guid}, Id: {guid.id}, Provider: '{guid.provider}'")

print(f"Metadata: {pm.to_json()}")

Expand Down
4 changes: 3 additions & 1 deletion plextraktsync/console.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from rich.console import Console

console = Console()
from plextraktsync.rich_addons import RichHighlighter

console = Console(highlighter=RichHighlighter())
print = console.print
16 changes: 15 additions & 1 deletion plextraktsync/factory.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from deprecated import deprecated

from plextraktsync.decorators.memoize import memoize
from plextraktsync.rich_addons import RichHighlighter


class Factory:
Expand Down Expand Up @@ -72,13 +73,16 @@ def sync(self):
def progressbar(self, enabled=True):
if enabled:
import warnings
from functools import partial

from tqdm import TqdmExperimentalWarning
from tqdm.rich import tqdm

from plextraktsync.console import console

warnings.filterwarnings("ignore", category=TqdmExperimentalWarning)

return tqdm
return partial(tqdm, options={'console': console})

return None

Expand Down Expand Up @@ -118,6 +122,16 @@ def walker(self):

return w

@memoize
def console_logger(self):
from rich.logging import RichHandler

from plextraktsync.console import console

handler = RichHandler(console=console, show_time=False, show_path=False, highlighter=RichHighlighter())

return handler

@memoize
def config(self):
from plextraktsync.config import CONFIG
Expand Down
7 changes: 3 additions & 4 deletions plextraktsync/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,11 @@ def initialize():
else:
log_level = logging.INFO
log_file = join(log_dir, CONFIG["logging"]["filename"])
log_format = "%(asctime)s %(levelname)s:%(message)s"

# messages with info and above are printed to stdout
console_handler = logging.StreamHandler(factory.progressbar())
console_handler = factory.console_logger()
console_handler.terminator = ""
console_handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
console_handler.setFormatter(logging.Formatter("%(message)s"))
console_handler.setLevel(logging.INFO)

# file handler can log down to debug messages
Expand All @@ -33,7 +32,7 @@ def initialize():
file_handler,
console_handler,
]
logging.basicConfig(format=log_format, handlers=handlers, level=log_level)
logging.basicConfig(handlers=handlers, level=log_level)

# Set debug for other components as well
if log_level == logging.DEBUG:
Expand Down
4 changes: 1 addition & 3 deletions plextraktsync/media.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,7 @@ def resolve_any(self, pm: PlexLibraryItem, show: Media = None):

def resolve_guid(self, guid: PlexGuid, show: Media = None):
if guid.provider in ["local", "none", "agents.none"]:
logger.warning(
f"{guid.pm.item}: Skipping guid {guid} because provider {guid.provider} has no external Id"
)
logger.warning(f"{guid.pm.item}: Skipping {guid} because provider {guid.provider} has no external Id")

return None

Expand Down
4 changes: 2 additions & 2 deletions plextraktsync/plex_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def guid_is_imdb_legacy(self):
return guid[0:2] == "tt" and guid[2:].isnumeric()

def __str__(self):
return self.guid
return f"<PlexGuid:{self.guid}>"


class PlexRatingCollection(dict):
Expand Down Expand Up @@ -375,7 +375,7 @@ def date_value(date):
def __repr__(self):
try:
guid = self.guids[0]
return f"<{guid.provider}:{guid.id}:{self.item}>"
return f"<{guid.provider}:{guid.id}:{str(self.item).strip('<>')}>"
except IndexError:
return f"<{self.item}>"

Expand Down
17 changes: 17 additions & 0 deletions plextraktsync/rich_addons.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from rich.highlighter import RegexHighlighter


class RichHighlighter(RegexHighlighter):
base_style = "repr."

highlights = [
r"(?P<path>\B(\/[\w\.\-\_\+]+)*\/)(?P<filename>[\w\.\-\_\+]*)?",
r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[\-\+]?\d+?)?\b|0x[0-9a-fA-F]*)",
r"(?P<attrib_name>[\w_]{1,50})=(?P<attrib_value>\"?[\w_]+\"?)?",
r"(?P<tag_start>\<)(?P<tag_name>(?:Movie|Episode|Show):\d+:[^>]+)(?P<tag_end>\>)",
r"(?P<tag_start>\<)(?P<tag_name>(?:PlexGuid|Guid):[^>]+)(?P<tag_end>\>)",
r"(?P<tag_start>\<)(?P<tag_name>(?:imdb|tmdb|tvdb|local):(?:\d+:)[^>]+)(?P<tag_end>\>)",
r"\b(?P<bool_true>True)\b|\b(?P<bool_false>False)\b|\b(?P<none>None)\b",
r"(?<![\\\w])(?P<str>b?\'\'\'.*?(?<!\\)\'\'\'|b?\'.*?(?<!\\)\'|b?\"\"\".*?(?<!\\)\"\"\"|b?\".*?(?<!\\)\")",
r"(?P<url>(file|https|http|ws|wss):\/\/[0-9a-zA-Z\$\-\_\+\!`\(\)\,\.\?\/\;\:\&\=\%\#]*)",
]
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ requests-oauthlib==1.3.1; python_version >= '2.7' and python_version not in '3.0
requests==2.27.1
rich==12.0.1
six==1.16.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
tqdm==4.63.1
tqdm==4.64.0
trakt==3.4.0
url-normalize==1.4.3; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4, 3.5'
urllib3==1.26.9
Expand Down

0 comments on commit d0ab386

Please sign in to comment.