Added basic logging feature to understand how is configuration loaded

This commit is contained in:
Pablo Carranza 2014-11-06 15:36:03 -05:00
parent 73d9882b64
commit a43cf16395
2 changed files with 25 additions and 0 deletions

View file

@ -17,16 +17,19 @@ import jrnl
import os
import argparse
import sys
import logging
xdg_config = os.environ.get('XDG_CONFIG_HOME')
CONFIG_PATH = os.path.join(xdg_config, "jrnl") if xdg_config else os.path.expanduser('~/.jrnl_config')
PYCRYPTO = install.module_exists("Crypto")
log = logging.getLogger(__name__)
def parse_args(args=None):
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--version', dest='version', action="store_true", help="prints version information and exits")
parser.add_argument('-ls', dest='ls', action="store_true", help="displays accessible journals")
parser.add_argument('-d', '--debug', dest='debug', action='store_true', help='execute in debug mode')
composing = parser.add_argument_group('Composing', 'To write an entry simply write it on the command line, e.g. "jrnl yesterday at 1pm: Went to the gym."')
composing.add_argument('text', metavar='', nargs="*")
@ -90,6 +93,7 @@ def decrypt(journal, filename=None):
def touch_journal(filename):
"""If filename does not exist, touch the file"""
if not os.path.exists(filename):
log.debug('Creating journal file %s', filename)
util.prompt("[Journal created at {0}]".format(filename))
open(filename, 'a').close()
@ -114,8 +118,15 @@ def update_config(config, new_config, scope, force_local=False):
config.update(new_config)
def configure_logger(debug=False):
logging.basicConfig(level=logging.DEBUG if debug else logging.INFO,
format='%(levelname)-8s %(name)-12s %(message)s')
logging.getLogger('parsedatetime').setLevel(logging.INFO) # disable parsedatetime debug logging
def run(manual_args=None):
args = parse_args(manual_args)
configure_logger(args.debug)
args.text = [p.decode('utf-8') if util.PY2 and not isinstance(p, unicode) else p for p in args.text]
if args.version:
version_str = "{0} version {1}".format(jrnl.__title__, jrnl.__version__)
@ -123,8 +134,10 @@ def run(manual_args=None):
sys.exit(0)
if not os.path.exists(CONFIG_PATH):
log.debug('Configuration file not found, installing jrnl...')
config = install.install_jrnl(CONFIG_PATH)
else:
log.debug('Reading configuration from file %s', CONFIG_PATH)
config = util.load_and_fix_json(CONFIG_PATH)
install.upgrade_config(config, config_path=CONFIG_PATH)
@ -132,6 +145,7 @@ def run(manual_args=None):
print(util.py2encode(list_journals(config)))
sys.exit(0)
log.debug('Using configuration "%s"', config)
original_config = config.copy()
# check if the configuration is supported by available modules
if config['encrypt'] and not PYCRYPTO:
@ -151,8 +165,10 @@ def run(manual_args=None):
except:
pass
log.debug('Using journal "%s"', journal_name)
journal_conf = config['journals'].get(journal_name)
if type(journal_conf) is dict: # We can override the default config on a by-journal basis
log.debug('Updating configuration with specific jourlnal overrides %s', journal_conf)
config.update(journal_conf)
else: # But also just give them a string to point to the journal file
config['journal'] = journal_conf
@ -163,6 +179,7 @@ def run(manual_args=None):
config['journal'] = os.path.expanduser(os.path.expandvars(config['journal']))
touch_journal(config['journal'])
log.debug('Using journal path %(journal)s', config)
mode_compose, mode_export = guess_mode(args, config)
# open journal file or folder
@ -204,6 +221,7 @@ def run(manual_args=None):
raw = " ".join(args.text).strip()
if util.PY2 and type(raw) is not unicode:
raw = raw.decode(sys.getfilesystemencoding())
log.debug('Appending raw line "%s" to journal "%s"', raw, journal_name)
journal.new_entry(raw)
util.prompt("[Entry added to {0} journal]".format(journal_name))
journal.write()

View file

@ -13,6 +13,7 @@ import tempfile
import subprocess
import codecs
import unicodedata
import logging
PY3 = sys.version_info[0] == 3
PY2 = sys.version_info[0] == 2
@ -22,6 +23,8 @@ STDOUT = sys.stdout
TEST = False
__cached_tz = None
log = logging.getLogger(__name__)
def getpass(prompt="Password: "):
if not TEST:
@ -96,18 +99,22 @@ def load_and_fix_json(json_path):
"""
with open(json_path) as f:
json_str = f.read()
log.debug('Configuration file %s read correctly', json_path)
config = None
try:
return json.loads(json_str)
except ValueError as e:
log.debug('Could not parse configuration %s: %s', json_str, e)
# Attempt to fix extra ,
json_str = re.sub(r",[ \n]*}", "}", json_str)
# Attempt to fix missing ,
json_str = re.sub(r"([^{,]) *\n *(\")", r"\1,\n \2", json_str)
try:
log.debug('Attempting to reload automatically fixed configuration file %s', json_str)
config = json.loads(json_str)
with open(json_path, 'w') as f:
json.dump(config, f, indent=2)
log.debug('Fixed configuration saved in file %s', json_path)
prompt("[Some errors in your jrnl config have been fixed for you.]")
return config
except ValueError as e: