diff --git a/SaveMyPlaylist.py b/SaveMyPlaylist.py index 1c57b55dc871497cda64acf0f1658f686fe30947..12dfffa69ccf6239c6e4d0a39e90eb9f8e00388c 100644 --- a/SaveMyPlaylist.py +++ b/SaveMyPlaylist.py @@ -1,6 +1,7 @@ from __future__ import unicode_literals import json +import logging import os import sys @@ -11,6 +12,31 @@ import youtube_dl VERSION = (2, 0, 0) +def prepare_logging() -> logging.Logger: + LOG_FORMAT = '[%(levelname)-7s] - %(asctime)s - %(message)s' + DATE_FORMAT = '%Y-%m-%d %H:%M:%S' + + LOG_FORMATTER = logging.Formatter(fmt=LOG_FORMAT, datefmt=DATE_FORMAT) + + logger = logging.getLogger('SaveMyPlaylist') + logger.setLevel(logging.DEBUG) + + outHandler = logging.StreamHandler(sys.stdout) + outHandler.setFormatter(LOG_FORMATTER) + outHandler.setLevel(logging.DEBUG) + outHandler.addFilter(lambda record: record.levelno <= logging.INFO) + logger.addHandler(outHandler) + + errHandler = logging.StreamHandler(sys.stderr) + errHandler.setFormatter(LOG_FORMATTER) + errHandler.setLevel(logging.WARNING) + logger.addHandler(errHandler) + return logger + + +logger = prepare_logging() + + class MyLogger(object): def debug(self, msg): pass @@ -24,7 +50,7 @@ class MyLogger(object): def my_hook(d): if d['status'] == 'finished': - print('Download finished!') + logger.info('Download finished!') class SaveMyPlaylist: @@ -39,8 +65,8 @@ class SaveMyPlaylist: ILLEGAL_CHARS = ['NUL', '\',''//', ':', '*', '"', '<', '>', '|'] def __init__(self, apiKey, playlistId): - print('### SaveMyPlaylist v{} ###'.format('.'.join(str(i) for i in VERSION))) - print('=============================\n') + logger.info('### SaveMyPlaylist v{} ###'.format('.'.join(str(i) for i in VERSION))) + logger.info('=============================') self._apiKey = apiKey self._playlistId = playlistId self._youtubeApi = googleapiclient.discovery.build(self.API_NAME, self.API_VERSION, developerKey=self._apiKey) @@ -54,7 +80,7 @@ class SaveMyPlaylist: pageItems, nextPageToken = self.__fetch_playlist_items(nextPageToken) items.extend(pageItems) - print('\n>>> Found {} items in playlist\n'.format(len(items))) + logger.info('>>> Found {} items in playlist'.format(len(items))) return items def __fetch_playlist_items(self, nextPageToken=None): @@ -75,13 +101,14 @@ class SaveMyPlaylist: response = request.execute() items = [] + logger.info('Found {} videos in playlist'.format(len(response['items']))) for item in response['items']: snippet = item['snippet'] title = snippet['title'] channel = snippet['channelTitle'] videoId = snippet['resourceId']['videoId'] items.append((channel, title, videoId)) - print('{} - {} (videoId: {})'.format(channel, title, videoId)) + logger.info('{} - {} (videoId: {})'.format(channel, title, videoId)) nextPageToken = None if 'nextPageToken' in response: @@ -91,22 +118,22 @@ class SaveMyPlaylist: def download_items(self, destinationFolder, debug=False): os.makedirs(destinationFolder, exist_ok=True) - print('>>> Scanning destination folder...') + logger.info('>>> Scanning destination folder...') downloadedVideos = [f for f in os.listdir(destinationFolder) if os.path.isfile(os.path.join(destinationFolder, f)) and f.endswith('.mp4')] - print('>>> Found {} videos in destination folder'.format(len(downloadedVideos))) + logger.info('>>> Found {} videos in destination folder'.format(len(downloadedVideos))) - print('\n>>> Started Downloading...') + logger.info('>>> Started Downloading...') newVideos = [] for idx, item in enumerate(self._items): fileName = '{} - {}.mp4'.format(item[self.TITLE], item[self.CHANNEL]) fileName = self.__escape_file_name(fileName) if fileName in downloadedVideos: - print('Skipping {}/{}: "{}" as it already exists'.format(idx + 1, len(self._items), fileName)) + logger.info('Skipping {}/{}: "{}" as it already exists'.format(idx + 1, len(self._items), fileName)) continue - print('Downloading {}/{}: "{}"'.format(idx + 1, len(self._items), fileName)) + logger.info('Downloading {}/{}: "{}"'.format(idx + 1, len(self._items), fileName)) newVideos.append(item) ydl_opts = { @@ -123,8 +150,8 @@ class SaveMyPlaylist: with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(['https://www.youtube.com/watch?v={}'.format(item[self.VIDEO_ID])]) - print('\n>>> Finished Downloading') - print('Downloaded {} new videos'.format(len(newVideos))) + logger.info('>>> Finished Downloading') + logger.info('Downloaded {} new videos'.format(len(newVideos))) def __escape_file_name(self, fileName): for char in self.ILLEGAL_CHARS: