Skip to content

Commit

Permalink
Merge pull request #75 from DankCity/73-use-appdirs-for-logs
Browse files Browse the repository at this point in the history
73 use appdirs for logs
  • Loading branch information
levi-rs authored Dec 5, 2016
2 parents 0a9c1f5 + b84ee42 commit 508ed33
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 51 deletions.
2 changes: 1 addition & 1 deletion circle.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,6 @@ test:

deployment:
production:
branch: master
branch: notmaster
commands:
- ssh $DEPLOY_HOST $DEPLOY_PATH/deploy.sh
4 changes: 3 additions & 1 deletion dankbot/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@

from ._version import get_versions
__version__ = get_versions()['version']
del get_versions

APPNAME = "dankbot"
APPAUTHOR = "DankCity"
72 changes: 48 additions & 24 deletions dankbot/cli.py
Original file line number Diff line number Diff line change
@@ -1,55 +1,79 @@


import os
import sys
import logging
from os import path
from configparser import ConfigParser
from logging.handlers import RotatingFileHandler

import appdirs

from dankbot.dankbot import DankBot
from dankbot import APPNAME, APPAUTHOR

DEFAULT_CONFIG = 'dankbot.ini'

LOG_FILE = "/var/log/dankbot/dankbot.log"

def load_config():
config = ConfigParser()
config_path = os.path.join(os.path.dirname(__file__), DEFAULT_CONFIG)
config.read(config_path)

return config

def configure_logger():

def configure_logger(log_config):
"""
Creates a rotating log
:param dir_path: String, path to current directory
:param config_dir_path: String, path to current directory
"""
# Create Logger object
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# Formatting
formatter = logging.Formatter('[%(levelname)s %(asctime)s] %(message)s')

# Set up STDOUT handler
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.DEBUG)
stdout_handler.setFormatter(formatter)
logger.addHandler(stdout_handler)

# Set up file logging with rotating file handler
rotate_fh = RotatingFileHandler(LOG_FILE, backupCount=5, maxBytes=1000000)
rotate_fh.setLevel(logging.DEBUG)
rotate_fh.setFormatter(formatter)
# Log to file if set in config
if log_config.getboolean('log_to_file'):
log_dir = log_config['directory'] or appdirs.user_log_dir(APPNAME, APPAUTHOR)
log_path = os.path.join(log_dir, log_config['file_name'])

# Create Logger object
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(stdout_handler)
logger.addHandler(rotate_fh)
# Create the logging directory if it doesn't exist
if not os.path.exists(log_dir): # pragma: no cover
os.makedirs(log_dir)

return logger
# Set up file logging with rotating file handler
backups = log_config.getint('backups')
max_bytes = log_config.getint('max_bytes')
rotate_fh = RotatingFileHandler(
log_path, backupCount=backups, maxBytes=max_bytes
)
rotate_fh.setLevel(logging.DEBUG)
rotate_fh.setFormatter(formatter)

logger.addHandler(rotate_fh)
else: # pragma: no cover
log_path = None

def main():
# Setup the logger
logger = configure_logger()
return logger, log_path

logger.info("Dankbot run starting")

def main():
# Load the configuration options
logger.info("Loading Dankbot Configuration")
config = ConfigParser()
config_path = path.join(path.dirname(__file__), u'dankbot.ini')
config.read(config_path)
config = load_config()

# Load the logger
logger, log_path = configure_logger(config['dankbot'])

logger.info("Dankbot run starting")
logger.info("Dankbot configuration loaded")
logger.info("Logging to: {0}".format(log_path)) # pylint: disable=W1202

try:
DankBot(config, logger).find_and_post_memes()
Expand Down
33 changes: 33 additions & 0 deletions dankbot/dankbot.sample.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
[dankbot]
# Leave directory blank and dankbot will determine the best place to
# log to your platform
log_to_file: true
directory:
file_name: dankbot.log
backups: 5
max_bytes: 1000000

[slack]
# Follow instructions at https://my.slack.com/services/new/bot
token: <put here>
channel: #random

[reddit]
# r/dankmemes, r/funnygifs, etc
subreddits: dankmemes, funnygifs

[imgur]
# Register at https://api.imgur.com/oauth2/addclient
# Select Anonymous usage
client_id: <your client ID>
client_secret: <your client secret>

[mysql]
# depricated, switching ti sqlite
database: <db>
username: <username>
password: <password>

[misc]
include_nsfw: false
max_memes: 3
Empty file removed dankbot/logs/dankbot.log
Empty file.
19 changes: 0 additions & 19 deletions dankbot/sample.dankbot.ini

This file was deleted.

11 changes: 6 additions & 5 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@
]
},
install_requires=[
'appdirs==1.4.0',
'configparser==3.5.0',
'imgurpython==1.1.7',
'mysqlclient==1.3.9',
'praw==3.6.0',
'retryz',
'slacker',
'mysqlclient',
'imgurpython',
'configparser>=3.5.0b2',
'retryz==0.1.8',
'slacker==0.9.30',
],
)
4 changes: 3 additions & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from dankbot import cli


@patch('dankbot.cli.DEFAULT_CONFIG', 'dankbot.sample.ini')
@patch('dankbot.cli.logging.getLogger')
@patch('dankbot.cli.RotatingFileHandler')
@patch('dankbot.cli.DankBot')
Expand All @@ -19,10 +20,11 @@ def test_main(dankbot, _, gl_mock):
assert dankbot.find_and_post_memes.called


@patch('dankbot.cli.DEFAULT_CONFIG', 'dankbot.sample.ini')
@patch('dankbot.cli.configure_logger')
@patch('dankbot.cli.DankBot')
def test_main_exception(dankbot, logger_mock):
logger_mock.return_value = logger_mock
logger_mock.return_value = logger_mock, None
dankbot.return_value = ValueError("Mock exception")

cli.main()
Expand Down

0 comments on commit 508ed33

Please sign in to comment.