Skip to content

Commit

Permalink
Merge branch 'for-log' into dev
Browse files Browse the repository at this point in the history
  • Loading branch information
tankywoo committed Mar 24, 2019
2 parents 55c38a1 + 8473830 commit 593783d
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 31 deletions.
7 changes: 4 additions & 3 deletions simiki/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def init_site(target_path):
initiator.init(ask=True)
except Exception:
# always in debug mode when init site
logging.exception("Initialize site with error:")
logger.exception("Initialize site with error:")
sys.exit(1)


Expand Down Expand Up @@ -123,6 +123,7 @@ def preview_site(host, port, dest, root, do_watch):
p_server = multiprocessing.Process(
target=preview,
args=(dest, root, host, port),
kwargs={'config': config},
name='ServerProcess'
)
p_server.start()
Expand Down Expand Up @@ -357,7 +358,7 @@ def install_theme(self):
shutil.rmtree(dest_theme)

copytree(src_theme, dest_theme)
logging.debug("Installing theme: {0}".format(self.config["theme"]))
logger.debug("Installing theme: {0}".format(self.config["theme"]))

def copy_attach(self):
"""Copy attach directory under root path to destination directory"""
Expand Down Expand Up @@ -394,7 +395,7 @@ def main(args=None):
config = parse_config(config_file)
except (Exception, YAMLError):
# always in debug mode when parse config
logging.exception("Parse config with error:")
logger.exception("Parse config with error:")
sys.exit(1)
level = logging.DEBUG if config["debug"] else logging.INFO
logging_init(level) # reload logger
Expand Down
8 changes: 5 additions & 3 deletions simiki/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

import tzlocal

logger = logging.getLogger(__name__)


class ConfigFileNotFound(Exception):
pass
Expand Down Expand Up @@ -85,9 +87,9 @@ def parse_config(config_file):
base_dir = os.getcwd()
_config_file = os.path.join(base_dir, sys.argv[1])
else:
logging.error("Use the template config file by default, "
"you can specify the config file to parse. \n"
"Usage: `python -m simiki.config [_config.yml]'")
logger.error("Use the template config file by default, "
"you can specify the config file to parse. \n"
"Usage: `python -m simiki.config [_config.yml]'")
sys.exit(1)

pprint(parse_config(_config_file))
17 changes: 9 additions & 8 deletions simiki/initiator.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from simiki.utils import (copytree, mkdir_p, listdir_nohidden)
from simiki.compat import raw_input

logger = logging.getLogger(__name__)
yes_answer = ('y', 'yes')


Expand All @@ -30,17 +31,17 @@ def __init__(self, config_file, target_path):
@staticmethod
def get_file(src, dst):
if os.path.exists(dst):
logging.warning("{0} exists".format(dst))
logger.warning("{0} exists".format(dst))
return

# Create parent directory
dst_directory = os.path.dirname(dst)
if not os.path.exists(dst_directory):
mkdir_p(dst_directory)
logging.info("Creating directory: {0}".format(dst_directory))
logger.info("Creating directory: {0}".format(dst_directory))

shutil.copyfile(src, dst)
logging.info("Creating file: {0}".format(dst))
logger.info("Creating file: {0}".format(dst))

def get_config_file(self):
dst_config_file = os.path.join(self.target_path, self.config_fn)
Expand Down Expand Up @@ -83,11 +84,11 @@ def get_default_theme(self, theme_path):
default_theme_name)
dst_theme = os.path.join(theme_path, default_theme_name)
if os.path.exists(dst_theme):
logging.warning('{0} exists'.format(dst_theme))
logger.warning('{0} exists'.format(dst_theme))
else:
copytree(src_theme, dst_theme)
logging.info("Copying default theme '{0}' to: {1}"
.format(default_theme_name, theme_path))
logger.info("Copying default theme '{0}' to: {1}"
.format(default_theme_name, theme_path))

def init(self, ask=False, **kwargs):
content_path = os.path.join(self.target_path, self.config["source"])
Expand All @@ -96,10 +97,10 @@ def init(self, ask=False, **kwargs):
theme_path = os.path.join(self.target_path, self.config['themes_dir'])
for path in (content_path, output_path, theme_path):
if os.path.exists(path):
logging.warning("{0} exists".format(path))
logger.warning("{0} exists".format(path))
else:
mkdir_p(path)
logging.info("Creating directory: {0}".format(path))
logger.info("Creating directory: {0}".format(path))

self.get_config_file()
self.get_fabfile()
Expand Down
6 changes: 4 additions & 2 deletions simiki/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import absolute_import, unicode_literals

import logging
from logging import getLogger, Formatter, StreamHandler
from logging import Formatter, StreamHandler

from simiki import utils
from simiki.compat import is_linux, is_osx
Expand Down Expand Up @@ -65,13 +65,15 @@ def _is_platform_allowed_ansi():
return False


def logging_init(level=None, logger=getLogger(),
def logging_init(level=None, name=None,
handler=StreamHandler(), use_color=True):
if use_color and _is_platform_allowed_ansi():
fmt = ANSIFormatter()
else:
fmt = NonANSIFormatter()
handler.setFormatter(fmt)

logger = logging.getLogger(name)
logger.addHandler(handler)

if level:
Expand Down
27 changes: 19 additions & 8 deletions simiki/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
import sys
import logging
import traceback
from simiki.compat import is_py2, unicode
from simiki.compat import is_py2, is_windows, unicode
if is_windows:
from simiki.log import logging_init

try:
import SimpleHTTPServer as http_server
Expand Down Expand Up @@ -35,6 +37,7 @@

URL_ROOT = None
PUBLIC_DIRECTORY = None
logger = logging.getLogger(__name__)


class Reuse_TCPServer(socket_server.TCPServer):
Expand Down Expand Up @@ -98,13 +101,21 @@ def do_GET(self):
http_server.SimpleHTTPRequestHandler.do_GET(self)


def preview(path, url_root, host='127.0.0.1', port=8000):
def preview(path, url_root, host='127.0.0.1', port=8000, **kwargs):
"""
:param path: directory path relative to current path
:param url_root: `root` setted in _config.yml
"""
global URL_ROOT, PUBLIC_DIRECTORY

if is_windows:
# since Windows lacks os.fork(), in multiprocessing, root logger
# is not the same as in main process, so we need to reinit the
# root logger in non-main process
config = kwargs.get('config')
lvl = logging.DEBUG if config["debug"] else logging.INFO
logging_init(level=lvl)

if not host:
host = '127.0.0.1'
if not port:
Expand All @@ -119,19 +130,19 @@ def preview(path, url_root, host='127.0.0.1', port=8000):
if os.path.exists(path):
os.chdir(path)
else:
logging.error("Path {} not exists".format(path))
logger.error("Path {} not exists".format(path))
try:
Handler = YARequestHandler
httpd = Reuse_TCPServer((host, port), Handler)
except (OSError, IOError) as e:
logging.error("Could not listen on port {0}\n{1}"
.format(port, traceback.format_exc()))
logger.error("Could not listen on port {0}\n{1}"
.format(port, traceback.format_exc()))
sys.exit(getattr(e, 'exitcode', 1))

logging.info("Serving at: http://{0}:{1}{2}/".format(host, port, url_root))
logging.info("Serving running... (Press CTRL-C to quit)")
logger.info("Serving at: http://{0}:{1}{2}/".format(host, port, url_root))
logger.info("Server running... (Press CTRL-C to quit)")
try:
httpd.serve_forever()
except (KeyboardInterrupt, SystemExit):
logging.info("Shutting down server")
logger.info("Shutting down server")
httpd.socket.close()
4 changes: 2 additions & 2 deletions simiki/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def emptytree(directory, exclude_list=None):
fp, unicode(e))
elif os.path.isfile(fp):
try:
logging.debug("Delete file %s", fp)
logger.debug("Delete file %s", fp)
os.remove(fp)
except OSError as e:
logger.error("Unable to delete file %s: %s", fp, unicode(e))
Expand Down Expand Up @@ -112,7 +112,7 @@ def write_file(filename, content):
"""Write content to file."""
_dir, _ = os.path.split(filename)
if not os.path.exists(_dir):
logging.debug("The directory %s not exists, create it", _dir)
logger.debug("The directory %s not exists, create it", _dir)
mkdir_p(_dir)
with io.open(filename, "wt", encoding="utf-8") as fd:
fd.write(content)
Expand Down
11 changes: 6 additions & 5 deletions simiki/watcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from simiki.generators import PageGenerator, CatalogGenerator
from simiki.utils import write_file

logger = logging.getLogger(__name__)
_site_config = None
_base_path = None

Expand All @@ -21,8 +22,8 @@ def wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception as e:
logging.error('Watcher has error, reloading...')
logging.debug(str(e))
logger.error('Watcher has error, reloading...')
logger.debug(str(e))
return wrapper


Expand Down Expand Up @@ -54,7 +55,7 @@ def generate_page(_file):

output_fname = YAPatternMatchingEventHandler.get_ofile(_file)
write_file(output_fname, html)
logging.debug('Regenerating: {0}'.format(_file))
logger.debug('Regenerating: {0}'.format(_file))

@staticmethod
def generate_catalog():
Expand All @@ -80,7 +81,7 @@ def generate_catalog():
"index.html"
)
write_file(ofile, html)
logging.debug('Regenerating catalog')
logger.debug('Regenerating catalog')

def process(self, event):
if event.event_type in ('moved',):
Expand Down Expand Up @@ -134,6 +135,6 @@ def watch(site_config, base_path):
while True:
time.sleep(1)
except (KeyboardInterrupt, SystemExit):
logging.info("Shutting down watcher")
logger.info("Shutting down watcher")
observer.stop()
observer.join()

0 comments on commit 593783d

Please sign in to comment.