Skip to content

Commit 7cf2c9b

Browse files
authored
Use logging instead of prints (#736)
1 parent 9587fca commit 7cf2c9b

4 files changed

Lines changed: 95 additions & 28 deletions

File tree

Procfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
web: python3 -m miss_islington
2-
worker: celery --app miss_islington.tasks.app worker --concurrency=1
2+
worker: celery --app miss_islington.tasks.app worker --concurrency=1 --loglevel=INFO

miss_islington/__main__.py

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import asyncio
2+
import logging
23
import os
3-
import sys
4-
import traceback
54

65
import aiohttp
76
import cachetools
@@ -16,6 +15,9 @@
1615

1716
from . import backport_pr, delete_branch
1817

18+
logging.basicConfig(level=logging.INFO)
19+
logger = logging.getLogger(__name__)
20+
1921
router = routing.Router(
2022
backport_pr.router, delete_branch.router
2123
)
@@ -29,7 +31,10 @@ async def main(request):
2931

3032
secret = os.environ.get("GH_SECRET")
3133
event = sansio.Event.from_http(request.headers, body, secret=secret)
32-
print("GH delivery ID", event.delivery_id, file=sys.stderr)
34+
logger.info(
35+
"received GitHub webhook",
36+
extra={"delivery_id": event.delivery_id, "event": event.event},
37+
)
3338
if event.event == "ping":
3439
return web.Response(status=200)
3540
async with aiohttp.ClientSession() as session:
@@ -50,25 +55,32 @@ async def main(request):
5055
await asyncio.sleep(1)
5156
await router.dispatch(event, gh)
5257
try:
53-
print(
54-
f"""\
55-
GH requests remaining: {gh.rate_limit.remaining}/{gh.rate_limit.limit}, \
56-
reset time: {gh.rate_limit.reset_datetime:%b-%d-%Y %H:%M:%S %Z}, \
57-
GH delivery ID {event.delivery_id} \
58-
"""
58+
logger.info(
59+
"GitHub rate limit",
60+
extra={
61+
"remaining": gh.rate_limit.remaining,
62+
"limit": gh.rate_limit.limit,
63+
"reset": gh.rate_limit.reset_datetime.isoformat(),
64+
"delivery_id": event.delivery_id,
65+
},
5966
)
6067
except AttributeError:
6168
pass
6269
return web.Response(status=200)
63-
except Exception as exc:
64-
traceback.print_exc(file=sys.stderr)
70+
except Exception:
71+
logger.exception("webhook handler crashed")
6572
return web.Response(status=500)
6673

6774

6875
@router.register("installation", action="created")
6976
async def repo_installation_added(event, gh, *args, **kwargs):
70-
# installation_id = event.data["installation"]["id"]
71-
print(f"App installed by {event.data['installation']['account']['login']}, installation_id: {event.data['installation']['id']}")
77+
logger.info(
78+
"app installed",
79+
extra={
80+
"account": event.data["installation"]["account"]["login"],
81+
"installation_id": event.data["installation"]["id"],
82+
},
83+
)
7284

7385

7486
sentry_sdk.init(dsn=os.environ.get("SENTRY_DSN"), integrations=[AioHttpIntegration()])

miss_islington/tasks.py

Lines changed: 62 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444

4545
@app.task()
4646
def setup_cpython_repo():
47-
print("Setting up CPython repository") # pragma: nocover
47+
logger.info("setting up CPython repository") # pragma: nocover
4848
if "cpython" not in os.listdir("."):
4949
subprocess.check_output(
5050
f"git clone https://{os.environ.get('GH_AUTH')}:x-oauth-basic@github.com/miss-islington/cpython.git".split()
@@ -59,9 +59,9 @@ def setup_cpython_repo():
5959
subprocess.check_output(
6060
f"git remote add upstream https://{os.environ.get('GH_AUTH')}:x-oauth-basic@github.com/python/cpython.git".split()
6161
)
62-
print("Finished setting up CPython Repo")
62+
logger.info("finished setting up CPython repository")
6363
else:
64-
print("cpython directory already exists")
64+
logger.info("cpython directory already exists")
6565

6666

6767
@app.task()
@@ -100,7 +100,16 @@ async def backport_task_asyncio(
100100
if "cpython" in os.listdir("."):
101101
os.chdir("./cpython")
102102
else:
103-
print(f"pwd: {os.getcwd()}, listdir: {os.listdir('.')}")
103+
logger.warning(
104+
"cpython directory not found",
105+
extra={
106+
"pwd": os.getcwd(),
107+
"listdir": os.listdir("."),
108+
"branch": branch,
109+
"commit_hash": commit_hash,
110+
"issue_number": issue_number,
111+
},
112+
)
104113

105114
await util.comment_on_pr(
106115
gh,
@@ -150,7 +159,14 @@ async def backport_task_asyncio(
150159
""",
151160
)
152161
await util.assign_pr_to_core_dev(gh, issue_number, merged_by)
153-
logger.exception("InvalidRepoException while backporting to %s", branch)
162+
logger.exception(
163+
"backport failed: invalid repo state",
164+
extra={
165+
"branch": branch,
166+
"commit_hash": commit_hash,
167+
"issue_number": issue_number,
168+
},
169+
)
154170
except cherry_picker.BranchCheckoutException as bce:
155171
await util.comment_on_pr(
156172
gh,
@@ -166,7 +182,15 @@ async def backport_task_asyncio(
166182
)
167183
await util.assign_pr_to_core_dev(gh, issue_number, merged_by)
168184
bce_state = cp.get_state_and_verify()
169-
print(bce_state, bce)
185+
logger.exception(
186+
"backport failed: branch checkout error",
187+
extra={
188+
"branch": branch,
189+
"commit_hash": commit_hash,
190+
"issue_number": issue_number,
191+
"state": bce_state.name,
192+
},
193+
)
170194
cp.abort_cherry_pick()
171195
except cherry_picker.CherryPickException as cpe:
172196
await util.comment_on_pr(
@@ -182,7 +206,15 @@ async def backport_task_asyncio(
182206
)
183207
await util.assign_pr_to_core_dev(gh, issue_number, merged_by)
184208
cpe_state = cp.get_state_and_verify()
185-
print(cpe_state, cpe)
209+
logger.exception(
210+
"backport failed: cherry-pick conflict",
211+
extra={
212+
"branch": branch,
213+
"commit_hash": commit_hash,
214+
"issue_number": issue_number,
215+
"state": cpe_state.name,
216+
},
217+
)
186218
cp.abort_cherry_pick()
187219
except cherry_picker.GitHubException as ghe:
188220
await util.comment_on_pr(
@@ -199,7 +231,15 @@ async def backport_task_asyncio(
199231
)
200232
await util.assign_pr_to_core_dev(gh, issue_number, merged_by)
201233
ghe_state = cp.get_state_and_verify()
202-
print(ghe_state, ghe)
234+
logger.exception(
235+
"backport failed: github error",
236+
extra={
237+
"branch": branch,
238+
"commit_hash": commit_hash,
239+
"issue_number": issue_number,
240+
"state": ghe_state.name,
241+
},
242+
)
203243
cp.abort_cherry_pick()
204244

205245

@@ -220,8 +260,14 @@ async def _delete_branch_task_asyncio(branch_name, pr_url, merged, *, installati
220260
if "cpython" in os.listdir("."):
221261
os.chdir("./cpython")
222262
else:
223-
print(f"Cannot delete branch: cpython repo not found. "
224-
f"pwd: {os.getcwd()}, listdir: {os.listdir('.')}")
263+
logger.warning(
264+
"cannot delete branch: cpython repo not found",
265+
extra={
266+
"branch": branch_name,
267+
"pwd": os.getcwd(),
268+
"listdir": os.listdir("."),
269+
},
270+
)
225271
return
226272

227273
if merged:
@@ -249,15 +295,18 @@ def _git_delete_branch(branch_name):
249295
["git", "push", "origin", "--delete", branch_name],
250296
stderr=subprocess.STDOUT
251297
)
252-
print(f"Deleted branch {branch_name}")
298+
logger.info("deleted branch", extra={"branch": branch_name})
253299
except subprocess.CalledProcessError as e:
254-
print(f"Failed to delete branch {branch_name}: {e.output.decode()}")
300+
logger.exception(
301+
"failed to delete branch",
302+
extra={"branch": branch_name, "output": e.output.decode()},
303+
)
255304
raise
256305

257306

258307
class InitRepoStep(bootsteps.StartStopStep):
259308
def start(self, c):
260-
print("Initialize the repository.")
309+
logger.info("initializing the repository")
261310
setup_cpython_repo()
262311

263312

miss_islington/util.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
import logging
12
import subprocess
23
import textwrap
34

5+
logger = logging.getLogger(__name__)
6+
47

58
async def comment_on_pr(gh, issue_number, message):
69
"""
@@ -10,7 +13,10 @@ async def comment_on_pr(gh, issue_number, message):
1013
message = textwrap.dedent(message)
1114
data = {"body": message}
1215
response = await gh.post(issue_comment_url, data=data)
13-
print(f"Commented at {response['html_url']}, message: {message}")
16+
logger.info(
17+
"commented on PR",
18+
extra={"issue_number": issue_number, "url": response["html_url"]},
19+
)
1420
return response
1521

1622

0 commit comments

Comments
 (0)