ソースを参照

Updated logger, so you can see who is what in the logs.

Steve Thielemann 5 年 前
コミット
58dd17c6d2
1 ファイル変更19 行追加12 行削除
  1. 19 12
      proxy.py

+ 19 - 12
proxy.py

@@ -47,6 +47,10 @@ def cleanANSI(line: str):
     return cleaner.sub("", line)
     # return re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?', '', line)
 
+class UserAdapter(logging.LoggerAdapter):
+    def process(self, msg, kwargs):
+        return '[{0}] {1}'.format(self.extra['game'].usergame, msg), kwargs
+
 
 from observer import Observer
 from flexible import PlayerInput, ProxyMenu
@@ -54,6 +58,7 @@ from galaxy import GameData, PORT_CLASSES, CLASSES_PORT
 
 
 class Game(protocol.Protocol):
+    
     def __init__(self):
         self.buffer = ""
         self.game = None
@@ -61,9 +66,11 @@ class Game(protocol.Protocol):
         self.gamedata = None
         self.to_player = True
         self.linestate = ""
+        baselog = logging.getLogger(__name__)
+        self.log = UserAdapter(baselog, {'game': self})
 
     def connectionMade(self):
-        log.info("Connected to Game Server")
+        self.log.info("Connected to Game Server")
         self.queue_player = self.factory.queue_player
         self.queue_game = self.factory.queue_game
         self.observer = self.factory.observer
@@ -73,7 +80,7 @@ class Game(protocol.Protocol):
 
     def show_game(self, game: tuple):
         self.usergame = game
-        log.info("## User-Game: {0}".format(game))
+        self.log.info("## User-Game: {0}".format(game))
         if game[1] is None:
             if self.gamedata is not None:
                 # start the save
@@ -91,7 +98,7 @@ class Game(protocol.Protocol):
     def playerDataReceived(self, chunk):
         if chunk is False:
             self.queue_player = None
-            log.info("Player: disconnected, close connection to game")
+            self.log.info("Player: disconnected, close connection to game")
             # I don't believe I need this if I'm using protocol.Factory
             self.factory.continueTrying = False
             self.transport.loseConnection()
@@ -99,14 +106,14 @@ class Game(protocol.Protocol):
             # Pass received data to the server
             if type(chunk) == str:
                 self.transport.write(chunk.encode('latin-1'))
-                log.debug(">> [{0}]".format(chunk))
+                self.log.debug(">> [{0}]".format(chunk))
             else:
                 self.transport.write(chunk)
-                log.debug(">> [{0}]".format(chunk.decode("latin-1", "ignore")))
+                self.log.debug(">> [{0}]".format(chunk.decode("latin-1", "ignore")))
             self.setPlayerReceived()
 
     def warpline(self, line: str):
-        log.debug("warp:", line)
+        self.log.debug("warp:", line)
         # 1 > 3 > 5 > 77 > 999
         last_sector = self.lastwarp
         line = line.replace("(", "").replace(")", "").replace(">", "").strip()
@@ -169,7 +176,7 @@ class Game(protocol.Protocol):
                 self.linestate = "cim"
 
     def sectorline(self, line: str):
-        log.debug("sector:", self.current_sector, ':', line)
+        self.log.debug("sector:", self.current_sector, ':', line)
         if line.startswith('Beacon  : '):
             pass # get beacon text
         elif line.startswith('Ports   : '):
@@ -217,14 +224,14 @@ class Game(protocol.Protocol):
             _, _, work = line.partition(':')
             work = work.strip().replace('(', '').replace(')', '').replace(' - ', ' ')
             parts = [ int(x) for x in work.split(' ')]
-            log.debug("Sectorline warps", parts)
+            self.log.debug("Sectorline warps", parts)
             self.gamedata.warp_to(self.current_sector, *parts)
             self.sector_state = 'normal'
             self.linestate = ''
 
     def portline(self, line: str):
         # Map these items to which keys
-        log.debug("portline({0}): {1}".format(self.current_sector, line))
+        self.log.debug("portline({0}): {1}".format(self.current_sector, line))
         mapto = { 'Fuel': 'fuel', 'Organics': 'org', 'Equipment': 'equ'}
 
         if '%' in line:
@@ -239,7 +246,7 @@ class Game(protocol.Protocol):
     def lineReceived(self, line: str):
         """ line received from the game. """
         if "log_lines" in config and config["log_lines"]:
-            log.debug("<< [{0}]".format(line))
+            self.log.debug("<< [{0}]".format(line))
 
         if "TradeWars Game Server" in line and "Copyright (C) EIS" in line:
             # We are not in a game
@@ -260,7 +267,7 @@ class Game(protocol.Protocol):
             _, _, sector = line.partition("]:[")
             sector, _, _ = sector.partition("]")
             self.current_sector = int(sector)
-            log.info("current sector: {0}".format(self.current_sector))
+            self.log.info("current sector: {0}".format(self.current_sector))
 
         if line.startswith("The shortest path (") or line.startswith("  TO > "):
             self.linestate = "warpline"
@@ -382,7 +389,7 @@ class Game(protocol.Protocol):
         self.observer.emit("prompt", self.getPrompt())
 
     def connectionLost(self, why):
-        log.info("Game connectionLost because: %s" % why)
+        self.log.info("Game connectionLost because: %s" % why)
         self.observer.emit("close", why)
         self.queue_game.put(False)
         self.transport.loseConnection()