Skip to content

Commit

Permalink
Correct colored logging (#3637)
Browse files Browse the repository at this point in the history
* Rewrite colered logging handler to use python logging

* Add all terminal colors and a format reset

* Add name to contributors list
  • Loading branch information
extink authored and douglascamata committed Aug 11, 2016
1 parent 543226e commit b033783
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 148 deletions.
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,4 @@
* Nivong
* kestel
* joaodragao
* extink
243 changes: 95 additions & 148 deletions pokemongo_bot/event_handlers/colored_logging_handler.py
Original file line number Diff line number Diff line change
@@ -1,171 +1,118 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import sys
import struct

import logging

from pokemongo_bot.event_manager import EventHandler


class ColoredLoggingHandler(EventHandler):
EVENT_COLOR_MAP = {
'api_error': 'red',
'bot_exit': 'red',
'bot_start': 'green',
'config_error': 'red',
'egg_already_incubating': 'yellow',
'egg_hatched': 'green',
'future_pokemon_release': 'yellow',
'incubate': 'green',
'incubator_already_used': 'yellow',
'inventory_full': 'yellow',
'item_discard_fail': 'red',
'item_discarded': 'green',
'keep_best_release': 'green',
'level_up': 'green',
'level_up_reward': 'green',
'location_cache_error': 'yellow',
'location_cache_ignored': 'yellow',
'login_failed': 'red',
'login_successful': 'green',
'lucky_egg_error': 'red',
'move_to_map_pokemon_encounter': 'green',
'move_to_map_pokemon_fail': 'red',
'next_egg_incubates': 'yellow',
'next_sleep': 'green',
'no_pokeballs': 'red',
'pokemon_appeared': 'yellow',
'pokemon_capture_failed': 'red',
'pokemon_caught': 'blue',
'pokemon_evolved': 'green',
'pokemon_fled': 'red',
'pokemon_inventory_full': 'red',
'pokemon_nickname_invalid': 'red',
'pokemon_not_in_range': 'yellow',
'pokemon_release': 'green',
'pokemon_vanished': 'red',
'pokestop_empty': 'yellow',
'pokestop_searching_too_often': 'yellow',
'rename_pokemon': 'green',
'skip_evolve': 'yellow',
'softban': 'red',
'spun_pokestop': 'cyan',
'threw_berry_failed': 'red',
'unknown_spin_result': 'red',
'unset_pokemon_nickname': 'red',
'vip_pokemon': 'red',
'api_error': 'red',
'bot_exit': 'red',
'bot_start': 'green',
'config_error': 'red',
'egg_already_incubating': 'yellow',
'egg_hatched': 'green',
'future_pokemon_release': 'yellow',
'incubate': 'green',
'incubator_already_used': 'yellow',
'inventory_full': 'yellow',
'item_discard_fail': 'red',
'item_discarded': 'green',
'keep_best_release': 'green',
'level_up': 'green',
'level_up_reward': 'green',
'location_cache_error': 'yellow',
'location_cache_ignored': 'yellow',
'login_failed': 'red',
'login_successful': 'green',
'lucky_egg_error': 'red',
'move_to_map_pokemon_encounter': 'green',
'move_to_map_pokemon_fail': 'red',
'next_egg_incubates': 'yellow',
'next_sleep': 'green',
'no_pokeballs': 'red',
'pokemon_appeared': 'yellow',
'pokemon_capture_failed': 'red',
'pokemon_caught': 'blue',
'pokemon_evolved': 'green',
'pokemon_fled': 'red',
'pokemon_inventory_full': 'red',
'pokemon_nickname_invalid': 'red',
'pokemon_not_in_range': 'yellow',
'pokemon_release': 'green',
'pokemon_vanished': 'red',
'pokestop_empty': 'yellow',
'pokestop_searching_too_often': 'yellow',
'rename_pokemon': 'green',
'skip_evolve': 'yellow',
'softban': 'red',
'spun_pokestop': 'cyan',
'threw_berry_failed': 'red',
'unknown_spin_result': 'red',
'unset_pokemon_nickname': 'red',
'vip_pokemon': 'red',

# event names for 'white' still here to remember that these events are already determined its color.
'arrived_at_cluster': 'white',
'arrived_at_fort': 'white',
'bot_sleep': 'white',
'catchable_pokemon': 'white',
'found_cluster': 'white',
'incubate_try': 'white',
'load_cached_location': 'white',
'location_found': 'white',
'login_started': 'white',
'lured_pokemon_found': 'white',
'move_to_map_pokemon_move_towards': 'white',
'move_to_map_pokemon_teleport_back': 'white',
'move_to_map_pokemon_updated_map': 'white',
'moving_to_fort': 'white',
'moving_to_lured_fort': 'white',
'pokemon_catch_rate': 'white',
'pokestop_on_cooldown': 'white',
'pokestop_out_of_range': 'white',
'polyline_request': 'white',
'position_update': 'white',
'set_start_location': 'white',
'softban_fix': 'white',
'softban_fix_done': 'white',
'spun_fort': 'white',
'threw_berry': 'white',
'threw_pokeball': 'white',
'used_lucky_egg': 'white'
'arrived_at_cluster': 'white',
'arrived_at_fort': 'white',
'bot_sleep': 'white',
'catchable_pokemon': 'white',
'found_cluster': 'white',
'incubate_try': 'white',
'load_cached_location': 'white',
'location_found': 'white',
'login_started': 'white',
'lured_pokemon_found': 'white',
'move_to_map_pokemon_move_towards': 'white',
'move_to_map_pokemon_teleport_back': 'white',
'move_to_map_pokemon_updated_map': 'white',
'moving_to_fort': 'white',
'moving_to_lured_fort': 'white',
'pokemon_catch_rate': 'white',
'pokemon_evolve_fail': 'white',
'pokestop_on_cooldown': 'white',
'pokestop_out_of_range': 'white',
'polyline_request': 'white',
'position_update': 'white',
'set_start_location': 'white',
'softban_fix': 'white',
'softban_fix_done': 'white',
'spun_fort': 'white',
'threw_berry': 'white',
'threw_pokeball': 'white',
'used_lucky_egg': 'white'
}
CONTINUOUS_EVENT_NAMES = [
'catchable_pokemon',
'moving_to_lured_fort',
'spun_fort'
]
COLOR_CODE = {
'red': '91',
'green': '92',
'yellow': '93',
'blue': '94',
'cyan': '96'
'gray': '\033[90m',
'red': '\033[91m',
'green': '\033[92m',
'yellow': '\033[93m',
'blue': '\033[94m',
'magenta': '\033[95m',
'cyan': '\033[96m',
'white': '\033[97m',
'reset': '\033[0m'
}

def __init__(self):
self._last_event = None
try:
# this `try ... except` is for ImportError on Windows
import fcntl
import termios
self._ioctl = fcntl.ioctl
self._TIOCGWINSZ = termios.TIOCGWINSZ
except ImportError:
self._ioctl = None
self._TIOCGWINSZ = None

def handle_event(self, event, sender, level, formatted_msg, data):
# Prepare message string
message = None
if formatted_msg:
try:
message = formatted_msg.decode('utf-8')
except UnicodeEncodeError:
message = formatted_msg
else:
message = '{}'.format(str(data))

# Replace message if necessary
if event == 'catchable_pokemon':
message = 'Something rustles nearby!'
logger = logging.getLogger(type(sender).__name__)

# Truncate previous line if same event continues
if event in ColoredLoggingHandler.CONTINUOUS_EVENT_NAMES and self._last_event == event and sys.stdout.isatty():
# Filling with "' ' * terminal_width" in order to completely clear last line
terminal_width = self._terminal_width()
if terminal_width:
sys.stdout.write('\r{}\r'.format(' ' * terminal_width))
else:
sys.stdout.write('\r')
else:
sys.stdout.write("\n")

color_name = None
if event in ColoredLoggingHandler.EVENT_COLOR_MAP:
color_name = ColoredLoggingHandler.EVENT_COLOR_MAP[event]

# Change color if necessary
color = self.COLOR_CODE['white']
if event in self.EVENT_COLOR_MAP:
color = self.COLOR_CODE[self.EVENT_COLOR_MAP[event]]
if event == 'egg_hatched' and data.get('pokemon', 'error') == 'error':
# `egg_hatched` event will be dispatched in both cases: hatched pokemon info is successfully taken or not.
# change color from 'green' to 'red' in case of error.
color_name = 'red'
color = self.COLOR_CODE['red']
formatted_msg = '{}{}{}'.format(color, formatted_msg, self.COLOR_CODE['reset'])

if color_name in ColoredLoggingHandler.COLOR_CODE:
sys.stdout.write(
'[{time}] \033[{color}m{message}\033[0m'.format(
time=time.strftime("%H:%M:%S"),
color=ColoredLoggingHandler.COLOR_CODE[color_name],
message=message
)
)
if formatted_msg:
message = "[{}] {}".format(event, formatted_msg)
else:
sys.stdout.write('[{time}] {message}'.format(
time=time.strftime("%H:%M:%S"),
message=message
))

sys.stdout.flush()
self._last_event = event

def _terminal_width(self):
if self._ioctl is None or self._TIOCGWINSZ is None:
return None

h, w, hp, wp = struct.unpack(str('HHHH'),
self._ioctl(0, self._TIOCGWINSZ,
struct.pack(str('HHHH'), 0, 0, 0, 0)))
return w
message = '{}: {}'.format(event, str(data))
getattr(logger, level)(message)

4 comments on commit b033783

@firzzen
Copy link

Choose a reason for hiding this comment

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

I'm no expert but this error seems related to this.

Traceback (most recent call last):
File "pokecli.py", line 41, in
from pokemongo_bot import PokemonGoBot, TreeConfigBuilder
File "/PokemonGo-Bot/pokemongo_bot/init.py", line 28, in
from pokemongo_bot.event_handlers import LoggingHandler, SocketIoHandler, ColoredLoggingHandler
File "/PokemonGo-Bot/pokemongo_bot/event_handlers/init.py", line 3, in
from colored_logging_handler import ColoredLoggingHandler
File "/PokemonGo-Bot/pokemongo_bot/event_handlers/colored_logging_handler.py", line 74
<<<<<<< HEAD
^
SyntaxError: invalid syntax

@DimaVIII
Copy link

Choose a reason for hiding this comment

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

Console log was much better without "[ SpinFort] [INFO] [spun_pokestop]".
Can you make a switch for to remove this for the config.json?

@relomy
Copy link

@relomy relomy commented on b033783 Aug 11, 2016

Choose a reason for hiding this comment

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

@firzzen that's a git problem on your end. Maybe try something like git checkout -- <file>.

@DimaVIII I'm pretty sure the only thing that wasn't there before in your quote was [INFO].

edit:

Never mind, I forgot I put all that back in mine. That's just part of all of the logging, sorry. I don't think there's a way to configure an option to change that.

@DimaVIII
Copy link

Choose a reason for hiding this comment

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

@relomy MY log (72622b4) before this update:

[00:23:30] Encountered Pokemon: Machop
[00:23:32] Teleporting back to previous location (40.7806239266, -73.9629481034)
[00:23:35] A wild Machop appeared! [CP 697] [Potential 0.56] [A/D/S 7/9/9]
[00:23:38] This is a VIP pokemon. Catch!!!
[00:23:38] Catch rate of 29.94 with Pokeball is low. Throwing Razz Berry (have 1)
[00:23:38] Threw a Razz Berry! Catch rate with Pokeball is now: 29.94
[00:23:39] Used Pokeball, with chance 44.91 (4 left)
[00:23:39] Machop capture failed.. trying again!
[00:23:41] Used Pokeball, with chance 44.91 (3 left)
[00:23:42] Machop capture failed.. trying again!
[00:23:45] Used Pokeball, with chance 44.91 (2 left)
[00:23:45] Machop capture failed.. trying again!
[00:23:48] Used Pokeball, with chance 44.91 (1 left)
[00:23:48] Captured Machop! [CP 697] [Potential 0.56] [7/9/9] [+210 exp]
[00:23:48] You now have 513 Machop candy!
[00:23:53] Moving towards Machop, 1.65km, left (9 minutes, 20 seconds)
[00:23:53] {'distance_unit': '', 'distance': '', 'current_position': (40.78047163113421, -73.96305556288512), 'last_position': (40.7806239265794, -73.96294810344476)}
[00:23:57] Pokemon Magikarp renamed to Magikarp80
[00:23:58] Keeping best 4 Machop, based on cp and iv
[00:23:58] Exchanged Machop [CP 697] [IV 0.56] for candy.
[00:23:58] Keeping best 6 Magikarp, based on cp and iv
[00:23:59] Exchanged Magikarp [CP 103] [IV 0.8] for candy.
[00:23:59] Skipping Recycling of Items. 326 space left in bag.
[00:23:59] Something rustles nearby!
[00:23:59] A wild Dodrio appeared! [CP 1068] [Potential 0.6] [A/D/S 7/12/8]
[00:24:03] Used Pokeball, with chance 12.77 (0 left)
[00:24:04] Dodrio capture failed.. trying again!
[00:24:06] No usable pokeballs found!
[00:24:11] Lured pokemon at fort The Puritan By Gaudens (5846b6509db24755af52c832ea6338b1.16)
[00:24:12] A wild Spearow appeared! [CP 502] [Potential 0.69] [A/D/S 11/11/9]
[00:24:15] Used Pokeball, with chance 28.29 (0 left)
[00:24:21] Teleporting to Dratini. (2.78km)
[00:24:21] Encountered Pokemon: Dratini
[00:24:24] Teleporting back to previous location (40.7804716311, -73.9630555629)
[00:24:26] A wild Dratini appeared! [CP 67] [Potential 0.64] [A/D/S 15/13/1]
[00:24:30] This is a VIP pokemon. Catch!!!
[00:24:30] Used Pokeball, with chance 74.17 (0 left)
[00:24:36] Moving towards Dratini, 2.78km, left (8 minutes, 29 seconds)
[00:24:36] {'distance_unit': '', 'distance': '', 'current_position': (40.78034540706027, -73.96318761895843), 'last_position': (40.78047163113421, -73.96305556288512)}
[00:24:40] Skipping Recycling of Items. 327 space left in bag.
[00:24:40] Something rustles nearby!
[00:24:41] A wild Dodrio appeared! [CP 1068] [Potential 0.6] [A/D/S 7/12/8]
[00:24:44] No usable pokeballs found!

Please sign in to comment.