Skip to content

Commit

Permalink
Replace all logger.log calls with events! (#2173)
Browse files Browse the repository at this point in the history
* bye bye `logger.log`, hello event system!

* fixing travis build

* trying to fix travis build

* test fixes

* updating remaining `logger.log` calls that should be replaced

* typo

* typos in IncubateEggs event

* improved fort loot event data

* fixing update_location event's distance unit

* fixing some events and log stuff

* adding missing fort_name parameter to lured_pokemon_found event

* fixing a variable inside an event formatted string

* fixing typos and utf8

* trying to fix tests with regards to float precision

* adding command to print all registered events and their parameters

* fixing tests yet again

* trying to fix unicode issues, arrgh!!!

* added a move to lured fort event

* better distance text in move to fort and fixing utf8 in spin fort task

* removing print from websocket server

* start embedded server before creating the socketio_handler

* I hate unicode

* rename and sleep events

* refactoring in how we emit events to avoid code repetition

* PokemonCatch task inherits from BaseTask

* go away, dirty logger.log!

* pep8 and removed logging handler name attribute

* good bye for the remaining logger.log calls

* bye logger module

* no more logger imports!

* removed last few loggers

* removing secret file and fixed variable name in follow cluster

* fixing kwargs for event emit

* trying to fix unicode handling one more time

* now it works!

* fixing more logs and removing debug unicode string

* no logs on websocket server yet

* adding a script to start a standalone websocket server

* more adjusted in websocket to support multiuser

* adding a fallback to logger.log issues a very verbose deprecation warning

* putting back compatibility with json based web ui
  • Loading branch information
douglascamata authored Aug 3, 2016
1 parent 02d9102 commit b2983f7
Show file tree
Hide file tree
Showing 31 changed files with 1,179 additions and 409 deletions.
98 changes: 69 additions & 29 deletions pokecli.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,26 @@
from geopy.exc import GeocoderQuotaExceeded

from pokemongo_bot import PokemonGoBot, TreeConfigBuilder
from pokemongo_bot import logger

if sys.version_info >= (2, 7, 9):
ssl._create_default_https_context = ssl._create_unverified_context

logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(name)10s] [%(levelname)s] %(message)s')
logger = logging.getLogger('cli')
logger.setLevel(logging.INFO)

def main():
logger.log('PokemonGO Bot v1.0', 'green')

logger.info('PokemonGO Bot v1.0')
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)

config = init_config()
if not config:
return
logger.log('Configuration initialized', 'yellow')
logger.info('Configuration initialized')

finished = False

Expand All @@ -65,51 +70,78 @@ def main():
bot.workers = tree
bot.metrics.capture_stats()

logger.log('Starting PokemonGo Bot....', 'green')
bot.event_manager.emit(
'bot_start',
sender=bot,
level='info',
formatted='Starting bot...'
)

while True:
bot.tick()

except KeyboardInterrupt:
logger.log('Exiting PokemonGo Bot', 'red')
bot.event_manager.emit(
'bot_exit',
sender=bot,
level='info',
formatted='Exiting bot.'
)
finished = True
report_summary(bot)
except (NotLoggedInException, ServerBusyOrOfflineException):
logger.log('[x] Error while connecting to the server, please wait %s minutes' % config.reconnecting_timeout, 'red')
time.sleep(config.reconnecting_timeout * 60)

except NotLoggedInException:
wait_time = config.reconnecting_timeout * 60
bot.event_manager.emit(
'api_error',
sender=bot,
level='info',
formmated='Log logged in, reconnecting in {:s}'.format(wait_time)
)
time.sleep(wait_time)
except ServerBusyOrOfflineException:
bot.event_manager.emit(
'api_error',
sender=bot,
level='info',
formatted='Server busy or offline'
)
except ServerSideRequestThrottlingException:
logger.log('Server is throttling, reconnecting in 30sec')
bot.event_manager.emit(
'api_error',
sender=bot,
level='info',
formatted='Server is throttling, reconnecting in 30 seconds'
)
time.sleep(30)
except GeocoderQuotaExceeded:
logger.log('[x] The given maps api key has gone over the requests limit.', 'red')
finished = True
except:
raise "Google Maps API key over requests limit."
except Exception as e:
# always report session summary and then raise exception
report_summary(bot)
raise
raise e

def report_summary(bot):
if bot.metrics.start_time is None:
return # Bot didn't actually start, no metrics to show.

metrics = bot.metrics
metrics.capture_stats()
logger.log('')
logger.log('Ran for {}'.format(metrics.runtime()), 'cyan')
logger.log('Total XP Earned: {} Average: {:.2f}/h'.format(metrics.xp_earned(), metrics.xp_per_hour()), 'cyan')
logger.log('Travelled {:.2f}km'.format(metrics.distance_travelled()), 'cyan')
logger.log('Visited {} stops'.format(metrics.visits['latest'] - metrics.visits['start']), 'cyan')
logger.log('Encountered {} pokemon, {} caught, {} released, {} evolved, {} never seen before'
logger.info('')
logger.info('Ran for {}'.format(metrics.runtime()))
logger.info('Total XP Earned: {} Average: {:.2f}/h'.format(metrics.xp_earned(), metrics.xp_per_hour()))
logger.info('Travelled {:.2f}km'.format(metrics.distance_travelled()))
logger.info('Visited {} stops'.format(metrics.visits['latest'] - metrics.visits['start']))
logger.info('Encountered {} pokemon, {} caught, {} released, {} evolved, {} never seen before'
.format(metrics.num_encounters(), metrics.num_captures(), metrics.releases,
metrics.num_evolutions(), metrics.num_new_mons()), 'cyan')
logger.log('Threw {} pokeball{}'.format(metrics.num_throws(), '' if metrics.num_throws() == 1 else 's'),
'cyan')
logger.log('Earned {} Stardust'.format(metrics.earned_dust()), 'cyan')
logger.log('')
metrics.num_evolutions(), metrics.num_new_mons()))
logger.info('Threw {} pokeball{}'.format(metrics.num_throws(), '' if metrics.num_throws() == 1 else 's'))
logger.info('Earned {} Stardust'.format(metrics.earned_dust()))
logger.info('')
if metrics.highest_cp is not None:
logger.log('Highest CP Pokemon: {}'.format(metrics.highest_cp['desc']), 'cyan')
logger.info('Highest CP Pokemon: {}'.format(metrics.highest_cp['desc']))
if metrics.most_perfect is not None:
logger.log('Most Perfect Pokemon: {}'.format(metrics.most_perfect['desc']), 'cyan')
logger.info('Most Perfect Pokemon: {}'.format(metrics.most_perfect['desc']))

def init_config():
parser = argparse.ArgumentParser()
Expand All @@ -126,11 +158,11 @@ def init_config():
with open(config_arg) as data:
load.update(json.load(data))
elif os.path.isfile(config_file):
logger.log('No config argument specified, checking for /configs/config.json', 'yellow')
logger.info('No config argument specified, checking for /configs/config.json')
with open(config_file) as data:
load.update(json.load(data))
else:
logger.log('Error: No /configs/config.json or specified config', 'red')
logger.info('Error: No /configs/config.json or specified config')

# Read passed in Arguments
required = lambda x: not x in load
Expand Down Expand Up @@ -228,7 +260,15 @@ def init_config():
type=str,
default=None
)

add_config(
parser,
load,
short_flag="-e",
long_flag="--show_events",
help="Show events",
type=bool,
default=False
)
add_config(
parser,
load,
Expand Down
Loading

3 comments on commit b2983f7

@rguedes
Copy link

@rguedes rguedes commented on b2983f7 Aug 4, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why remove colors from logs ??

@BoGnY
Copy link

@BoGnY BoGnY commented on b2983f7 Aug 4, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

because he is convinced that a logging event manager is more useful of colored logs, and also than text log files..
as well as he having worsened the amount of log displayed by the bot (now filled with useless and confusing text, spam logs), he worsened viewing and ease of understanding of what made the bot went to fuck off...

the worst commit of ever..

worst:
worst

better:
best

the same logs with version pre and post commit..

I really can not understand the meaning...
perhaps, if he create a config value on config.json so that everyone chooses what kind of log (previous logger or event manager) wanted to have, it was better..

@rguedes
Copy link

@rguedes rguedes commented on b2983f7 Aug 4, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

He can use both. Use event log and color log.

Please sign in to comment.