Skip to content

Commit

Permalink
Make global log variable in modules private
Browse files Browse the repository at this point in the history
  • Loading branch information
Rapptz committed Aug 22, 2021
1 parent 6268cad commit ea2d972
Show file tree
Hide file tree
Showing 11 changed files with 147 additions and 147 deletions.
24 changes: 12 additions & 12 deletions discord/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,20 +76,20 @@
Coro = TypeVar('Coro', bound=Callable[..., Coroutine[Any, Any, Any]])


log: logging.Logger = logging.getLogger(__name__)
_log = logging.getLogger(__name__)

def _cancel_tasks(loop: asyncio.AbstractEventLoop) -> None:
tasks = {t for t in asyncio.all_tasks(loop=loop) if not t.done()}

if not tasks:
return

log.info('Cleaning up after %d tasks.', len(tasks))
_log.info('Cleaning up after %d tasks.', len(tasks))
for task in tasks:
task.cancel()

loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
log.info('All tasks finished cancelling.')
_log.info('All tasks finished cancelling.')

for task in tasks:
if task.cancelled():
Expand All @@ -106,7 +106,7 @@ def _cleanup_loop(loop: asyncio.AbstractEventLoop) -> None:
_cancel_tasks(loop)
loop.run_until_complete(loop.shutdown_asyncgens())
finally:
log.info('Closing the event loop.')
_log.info('Closing the event loop.')
loop.close()

class Client:
Expand Down Expand Up @@ -237,7 +237,7 @@ def __init__(

if VoiceClient.warn_nacl:
VoiceClient.warn_nacl = False
log.warning("PyNaCl is not installed, voice will NOT be supported")
_log.warning("PyNaCl is not installed, voice will NOT be supported")

# internals

Expand Down Expand Up @@ -363,7 +363,7 @@ def _schedule_event(self, coro: Callable[..., Coroutine[Any, Any, Any]], event_n
return asyncio.create_task(wrapped, name=f'discord.py: {event_name}')

def dispatch(self, event: str, *args: Any, **kwargs: Any) -> None:
log.debug('Dispatching event %s', event)
_log.debug('Dispatching event %s', event)
method = 'on_' + event

listeners = self._listeners.get(event)
Expand Down Expand Up @@ -468,7 +468,7 @@ async def login(self, token: str) -> None:
passing status code.
"""

log.info('logging in using static token')
_log.info('logging in using static token')

data = await self.http.static_login(token.strip())
self._connection.user = ClientUser(state=self._connection, data=data)
Expand Down Expand Up @@ -511,7 +511,7 @@ async def connect(self, *, reconnect: bool = True) -> None:
while True:
await self.ws.poll_event()
except ReconnectWebSocket as e:
log.info('Got a request to %s the websocket.', e.op)
_log.info('Got a request to %s the websocket.', e.op)
self.dispatch('disconnect')
ws_params.update(sequence=self.ws.sequence, resume=e.resume, session=self.ws.session_id)
continue
Expand Down Expand Up @@ -550,7 +550,7 @@ async def connect(self, *, reconnect: bool = True) -> None:
raise

retry = backoff.delay()
log.exception("Attempting a reconnect in %.2fs", retry)
_log.exception("Attempting a reconnect in %.2fs", retry)
await asyncio.sleep(retry)
# Always try to RESUME the connection
# If the connection is not RESUME-able then the gateway will invalidate the session.
Expand Down Expand Up @@ -652,10 +652,10 @@ def stop_loop_on_completion(f):
try:
loop.run_forever()
except KeyboardInterrupt:
log.info('Received signal to terminate bot and event loop.')
_log.info('Received signal to terminate bot and event loop.')
finally:
future.remove_done_callback(stop_loop_on_completion)
log.info('Cleaning up tasks.')
_log.info('Cleaning up tasks.')
_cleanup_loop(loop)

if not future.cancelled():
Expand Down Expand Up @@ -1021,7 +1021,7 @@ async def on_ready():
raise TypeError('event registered must be a coroutine function')

setattr(self, coro.__name__, coro)
log.debug('%s has successfully been registered as an event', coro.__name__)
_log.debug('%s has successfully been registered as an event', coro.__name__)
return coro

async def change_presence(
Expand Down
2 changes: 1 addition & 1 deletion discord/ext/tasks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
from discord.backoff import ExponentialBackoff
from discord.utils import MISSING

log = logging.getLogger(__name__)
_log = logging.getLogger(__name__)

__all__ = (
'loop',
Expand Down
68 changes: 34 additions & 34 deletions discord/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
from .enums import SpeakingState
from .errors import ConnectionClosed, InvalidArgument

log = logging.getLogger(__name__)
_log = logging.getLogger(__name__)

__all__ = (
'DiscordWebSocket',
Expand Down Expand Up @@ -101,7 +101,7 @@ async def block(self):
async with self.lock:
delta = self.get_delay()
if delta:
log.warning('WebSocket in shard ID %s is ratelimited, waiting %.2f seconds', self.shard_id, delta)
_log.warning('WebSocket in shard ID %s is ratelimited, waiting %.2f seconds', self.shard_id, delta)
await asyncio.sleep(delta)


Expand Down Expand Up @@ -129,20 +129,20 @@ def __init__(self, *args, **kwargs):
def run(self):
while not self._stop_ev.wait(self.interval):
if self._last_recv + self.heartbeat_timeout < time.perf_counter():
log.warning("Shard ID %s has stopped responding to the gateway. Closing and restarting.", self.shard_id)
_log.warning("Shard ID %s has stopped responding to the gateway. Closing and restarting.", self.shard_id)
coro = self.ws.close(4000)
f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)

try:
f.result()
except Exception:
log.exception('An error occurred while stopping the gateway. Ignoring.')
_log.exception('An error occurred while stopping the gateway. Ignoring.')
finally:
self.stop()
return

data = self.get_payload()
log.debug(self.msg, self.shard_id, data['d'])
_log.debug(self.msg, self.shard_id, data['d'])
coro = self.ws.send_heartbeat(data)
f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)
try:
Expand All @@ -161,7 +161,7 @@ def run(self):
else:
stack = ''.join(traceback.format_stack(frame))
msg = f'{self.block_msg}\nLoop thread traceback (most recent call last):\n{stack}'
log.warning(msg, self.shard_id, total)
_log.warning(msg, self.shard_id, total)

except Exception:
self.stop()
Expand All @@ -185,7 +185,7 @@ def ack(self):
self._last_ack = ack_time
self.latency = ack_time - self._last_send
if self.latency > 10:
log.warning(self.behind_msg, self.shard_id, self.latency)
_log.warning(self.behind_msg, self.shard_id, self.latency)

class VoiceKeepAliveHandler(KeepAliveHandler):
def __init__(self, *args, **kwargs):
Expand Down Expand Up @@ -330,7 +330,7 @@ async def from_client(cls, client, *, initial=False, gateway=None, shard_id=None

client._connection._update_references(ws)

log.debug('Created websocket connected to %s', gateway)
_log.debug('Created websocket connected to %s', gateway)

# poll event for OP Hello
await ws.poll_event()
Expand Down Expand Up @@ -403,7 +403,7 @@ async def identify(self):

await self.call_hooks('before_identify', self.shard_id, initial=self._initial_identify)
await self.send_as_json(payload)
log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)
_log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)

async def resume(self):
"""Sends the RESUME packet."""
Expand All @@ -417,7 +417,7 @@ async def resume(self):
}

await self.send_as_json(payload)
log.info('Shard ID %s has sent the RESUME payload.', self.shard_id)
_log.info('Shard ID %s has sent the RESUME payload.', self.shard_id)

async def received_message(self, msg, /):
self.log_receive(msg)
Expand All @@ -432,7 +432,7 @@ async def received_message(self, msg, /):
self._buffer = bytearray()
msg = utils.from_json(msg)

log.debug('For Shard ID %s: WebSocket Event: %s', self.shard_id, msg)
_log.debug('For Shard ID %s: WebSocket Event: %s', self.shard_id, msg)
event = msg.get('t')
if event:
self._dispatch('socket_event_type', event)
Expand All @@ -451,7 +451,7 @@ async def received_message(self, msg, /):
# "reconnect" can only be handled by the Client
# so we terminate our connection and raise an
# internal exception signalling to reconnect.
log.debug('Received RECONNECT opcode.')
_log.debug('Received RECONNECT opcode.')
await self.close()
raise ReconnectWebSocket(self.shard_id)

Expand Down Expand Up @@ -481,11 +481,11 @@ async def received_message(self, msg, /):

self.sequence = None
self.session_id = None
log.info('Shard ID %s session has been invalidated.', self.shard_id)
_log.info('Shard ID %s session has been invalidated.', self.shard_id)
await self.close(code=1000)
raise ReconnectWebSocket(self.shard_id, resume=False)

log.warning('Unknown OP code %s.', op)
_log.warning('Unknown OP code %s.', op)
return

if event == 'READY':
Expand All @@ -494,20 +494,20 @@ async def received_message(self, msg, /):
self.session_id = data['session_id']
# pass back shard ID to ready handler
data['__shard_id__'] = self.shard_id
log.info('Shard ID %s has connected to Gateway: %s (Session ID: %s).',
_log.info('Shard ID %s has connected to Gateway: %s (Session ID: %s).',
self.shard_id, ', '.join(trace), self.session_id)

elif event == 'RESUMED':
self._trace = trace = data.get('_trace', [])
# pass back the shard ID to the resumed handler
data['__shard_id__'] = self.shard_id
log.info('Shard ID %s has successfully RESUMED session %s under trace %s.',
_log.info('Shard ID %s has successfully RESUMED session %s under trace %s.',
self.shard_id, self.session_id, ', '.join(trace))

try:
func = self._discord_parsers[event]
except KeyError:
log.debug('Unknown event %s.', event)
_log.debug('Unknown event %s.', event)
else:
func(data)

Expand Down Expand Up @@ -561,10 +561,10 @@ async def poll_event(self):
elif msg.type is aiohttp.WSMsgType.BINARY:
await self.received_message(msg.data)
elif msg.type is aiohttp.WSMsgType.ERROR:
log.debug('Received %s', msg)
_log.debug('Received %s', msg)
raise msg.data
elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.CLOSING, aiohttp.WSMsgType.CLOSE):
log.debug('Received %s', msg)
_log.debug('Received %s', msg)
raise WebSocketClosure
except (asyncio.TimeoutError, WebSocketClosure) as e:
# Ensure the keep alive handler is closed
Expand All @@ -573,15 +573,15 @@ async def poll_event(self):
self._keep_alive = None

if isinstance(e, asyncio.TimeoutError):
log.info('Timed out receiving packet. Attempting a reconnect.')
_log.info('Timed out receiving packet. Attempting a reconnect.')
raise ReconnectWebSocket(self.shard_id) from None

code = self._close_code or self.socket.close_code
if self._can_handle_close():
log.info('Websocket closed with %s, attempting a reconnect.', code)
_log.info('Websocket closed with %s, attempting a reconnect.', code)
raise ReconnectWebSocket(self.shard_id) from None
else:
log.info('Websocket closed with %s, cannot reconnect.', code)
_log.info('Websocket closed with %s, cannot reconnect.', code)
raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None

async def debug_send(self, data, /):
Expand Down Expand Up @@ -630,7 +630,7 @@ async def change_presence(self, *, activity=None, status=None, since=0.0):
}

sent = utils.to_json(payload)
log.debug('Sending "%s" to change status', sent)
_log.debug('Sending "%s" to change status', sent)
await self.send(sent)

async def request_chunks(self, guild_id, query=None, *, limit, user_ids=None, presences=False, nonce=None):
Expand Down Expand Up @@ -666,7 +666,7 @@ async def voice_state(self, guild_id, channel_id, self_mute=False, self_deaf=Fal
}
}

log.debug('Updating our voice state to %s.', payload)
_log.debug('Updating our voice state to %s.', payload)
await self.send_as_json(payload)

async def close(self, code=4000):
Expand Down Expand Up @@ -734,7 +734,7 @@ async def _hook(self, *args):
pass

async def send_as_json(self, data):
log.debug('Sending voice websocket frame: %s.', data)
_log.debug('Sending voice websocket frame: %s.', data)
await self.ws.send_str(utils.to_json(data))

send_heartbeat = send_as_json
Expand Down Expand Up @@ -820,7 +820,7 @@ async def speak(self, state=SpeakingState.voice):
await self.send_as_json(payload)

async def received_message(self, msg):
log.debug('Voice websocket frame received: %s', msg)
_log.debug('Voice websocket frame received: %s', msg)
op = msg['op']
data = msg.get('d')

Expand All @@ -829,7 +829,7 @@ async def received_message(self, msg):
elif op == self.HEARTBEAT_ACK:
self._keep_alive.ack()
elif op == self.RESUMED:
log.info('Voice RESUME succeeded.')
_log.info('Voice RESUME succeeded.')
elif op == self.SESSION_DESCRIPTION:
self._connection.mode = data['mode']
await self.load_secret_key(data)
Expand All @@ -852,23 +852,23 @@ async def initial_connection(self, data):
struct.pack_into('>I', packet, 4, state.ssrc)
state.socket.sendto(packet, (state.endpoint_ip, state.voice_port))
recv = await self.loop.sock_recv(state.socket, 70)
log.debug('received packet in initial_connection: %s', recv)
_log.debug('received packet in initial_connection: %s', recv)

# the ip is ascii starting at the 4th byte and ending at the first null
ip_start = 4
ip_end = recv.index(0, ip_start)
state.ip = recv[ip_start:ip_end].decode('ascii')

state.port = struct.unpack_from('>H', recv, len(recv) - 2)[0]
log.debug('detected ip: %s port: %s', state.ip, state.port)
_log.debug('detected ip: %s port: %s', state.ip, state.port)

# there *should* always be at least one supported mode (xsalsa20_poly1305)
modes = [mode for mode in data['modes'] if mode in self._connection.supported_modes]
log.debug('received supported encryption modes: %s', ", ".join(modes))
_log.debug('received supported encryption modes: %s', ", ".join(modes))

mode = modes[0]
await self.select_protocol(state.ip, state.port, mode)
log.info('selected the voice protocol for use (%s)', mode)
_log.info('selected the voice protocol for use (%s)', mode)

@property
def latency(self):
Expand All @@ -886,7 +886,7 @@ def average_latency(self):
return sum(heartbeat.recent_ack_latencies) / len(heartbeat.recent_ack_latencies)

async def load_secret_key(self, data):
log.info('received secret key for voice connection')
_log.info('received secret key for voice connection')
self.secret_key = self._connection.secret_key = data.get('secret_key')
await self.speak()
await self.speak(False)
Expand All @@ -897,10 +897,10 @@ async def poll_event(self):
if msg.type is aiohttp.WSMsgType.TEXT:
await self.received_message(utils.from_json(msg.data))
elif msg.type is aiohttp.WSMsgType.ERROR:
log.debug('Received %s', msg)
_log.debug('Received %s', msg)
raise ConnectionClosed(self.ws, shard_id=None) from msg.data
elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSING):
log.debug('Received %s', msg)
_log.debug('Received %s', msg)
raise ConnectionClosed(self.ws, shard_id=None, code=self._close_code)

async def close(self, code=1000):
Expand Down
Loading

0 comments on commit ea2d972

Please sign in to comment.