Skip to content

Commit 79c582d

Browse files
authored
Merge pull request #170 from creativecommons/logging-sync-etc
Logging sync etc
2 parents cebc132 + 8e3a77b commit 79c582d

14 files changed

+381
-411
lines changed

ccos/data/get_community_team_data.py

+12-15
Original file line numberDiff line numberDiff line change
@@ -15,33 +15,31 @@
1515
import asana
1616

1717
# First-party/Local
18-
from ccos import log
18+
import ccos.log
1919

2020
ASANA_WORKSPACE_GID = "133733285600979"
2121
ASANA_PROJECT_GID = "1172465506923661"
2222

2323
log_name = os.path.basename(os.path.splitext(inspect.stack()[-1].filename)[0])
24-
logger = logging.getLogger(log_name)
25-
log.reset_handler()
24+
LOG = logging.getLogger(log_name)
25+
ccos.log.reset_handler()
2626

2727

2828
def setup_asana_client():
29-
logger.log(logging.INFO, "Setting up Asana client...")
29+
LOG.info("Setting up Asana client...")
3030
try:
3131
asana_token = os.environ["ADMIN_ASANA_TOKEN"]
3232
except KeyError:
33-
logger.critical("missin ADMIN_ASANA_TOKEN environment variable")
33+
LOG.critical("missin ADMIN_ASANA_TOKEN environment variable")
3434
sys.exit(1)
3535
asana_client = asana.Client.access_token(asana_token)
3636
try:
3737
# Perform simple API operation to test authentication
3838
asana_client.workspaces.get_workspace(ASANA_WORKSPACE_GID)
3939
except asana.error.NoAuthorizationError as e:
40-
logger.critical(
41-
f"{e.status} {e.message} (is ADMIN_ASANA_TOKEN valid?)"
42-
)
40+
LOG.critical(f"{e.status} {e.message} (is ADMIN_ASANA_TOKEN valid?)")
4341
sys.exit(1)
44-
logger.log(logging.INFO, "done.")
42+
LOG.info("done.")
4543
return asana_client
4644

4745

@@ -80,15 +78,15 @@ def generate_databag(asana_client):
8078
}
8179
"""
8280

83-
logger.log(logging.INFO, "Pulling from Asana and generating databag...")
81+
LOG.info("Pulling from Asana and generating databag...")
8482
databag = {"projects": [], "community_builders": []}
8583

8684
members = asana_client.tasks.find_by_section(
8785
ASANA_PROJECT_GID, opt_fields=["name", "custom_fields"]
8886
)
89-
logger.log(logging.INFO, "Team members pulled.")
87+
LOG.info("Team members pulled.")
9088

91-
logger.log(logging.INFO, "Processing team members...")
89+
LOG.info("Processing team members...")
9290
for member in members:
9391
if member["name"] == "":
9492
continue # Sometimes blank names come up
@@ -123,7 +121,7 @@ def generate_databag(asana_client):
123121
)
124122
break
125123

126-
logger.log(logging.INFO, "Done.")
124+
LOG.info("Done.")
127125
return databag
128126

129127

@@ -183,8 +181,7 @@ def verify_databag(databag, repo_names):
183181
databag_repos = project["repos"].split(",")
184182
for databag_repo in databag_repos:
185183
if databag_repo not in repo_names:
186-
logger.log(
187-
logging.ERROR,
184+
LOG.error(
188185
f'"{project["name"]}" contains invalid reposiotry:'
189186
f' "{databag_repo}"',
190187
)

ccos/data/get_repo_data.py

+10-14
Original file line numberDiff line numberDiff line change
@@ -13,36 +13,36 @@
1313
from github.GithubException import GithubException, UnknownObjectException
1414

1515
# First-party/Local
16-
from ccos import log
16+
import ccos.log
1717
from ccos.data.push_data_via_git import GITHUB_ORGANIZATION, GITHUB_TOKEN
1818

1919
CC_METADATA_FILE_NAME = ".cc-metadata.yml"
2020

2121
log_name = os.path.basename(os.path.splitext(inspect.stack()[-1].filename)[0])
22-
logger = logging.getLogger(log_name)
23-
log.reset_handler()
22+
LOG = logging.getLogger(log_name)
23+
ccos.log.reset_handler()
2424

2525

2626
def set_up_github_client():
27-
logger.log(logging.INFO, "Setting up GitHub client...")
27+
LOG.info("Setting up GitHub client...")
2828
github_client = Github(GITHUB_TOKEN)
2929
return github_client
3030

3131

3232
def get_cc_organization(github_client):
33-
logger.log(logging.INFO, "Getting CC's GitHub organization...")
33+
LOG.info("Getting CC's GitHub organization...")
3434
cc = github_client.get_organization(GITHUB_ORGANIZATION)
3535
return cc
3636

3737

3838
def get_repositories(organization):
39-
logger.log(logging.INFO, "Getting CC's repos...")
39+
LOG.info("Getting CC's repos...")
4040
repos = organization.get_repos()
4141
return repos
4242

4343

4444
def get_repo_github_data(repo):
45-
logger.log(logging.INFO, "Getting data for this repo...")
45+
LOG.info("Getting data for this repo...")
4646
repo_github_data = {
4747
"id": repo.id,
4848
"name": repo.name,
@@ -69,7 +69,7 @@ def get_repo_github_data(repo):
6969

7070

7171
def get_repo_cc_metadata(repo):
72-
logger.log(logging.INFO, "Getting CC metadata for this repo...")
72+
LOG.info("Getting CC metadata for this repo...")
7373
try:
7474
cc_metadata_file = repo.get_contents(CC_METADATA_FILE_NAME)
7575
except (UnknownObjectException, GithubException):
@@ -89,9 +89,7 @@ def get_repo_data_list(repos):
8989
total = repos.totalCount
9090

9191
for repo in repos:
92-
logger.log(
93-
logging.INFO, f"Processing {count} of {total}{repo.name}"
94-
)
92+
LOG.info(f"Processing {count} of {total}{repo.name}")
9593
if not repo.private:
9694
repo_cc_metadata = get_repo_cc_metadata(repo)
9795
is_engineering_project = repo_cc_metadata.get(
@@ -104,9 +102,7 @@ def get_repo_data_list(repos):
104102
repo_data = {**repo_github_data, **repo_cc_metadata}
105103
repo_data_list.append(repo_data)
106104
else:
107-
logger.log(
108-
logging.INFO, "Not an active engineering project, skipping"
109-
)
105+
LOG.info("Not an active engineering project, skipping")
110106
count += 1
111107
return sorted(repo_data_list, key=lambda k: k["name"].lower())
112108

ccos/data/push_data_via_git.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,13 @@
66
import json
77
import logging
88
import os
9-
import tempfile
9+
from tempfile import TemporaryDirectory
1010

1111
# Third-party
1212
import git
1313

1414
# First-party/Local
15-
from ccos import log
15+
import ccos.log
1616

1717
GIT_USER_NAME = "CC creativecommons.github.io Bot"
1818
GIT_USER_EMAIL = "cc-creativecommons-github-io-bot@creativecommons.org"
@@ -30,34 +30,34 @@
3030
JSON_FILE_DIR = "databags"
3131

3232
log_name = os.path.basename(os.path.splitext(inspect.stack()[-1].filename)[0])
33-
logger = logging.getLogger(log_name)
34-
log.reset_handler()
33+
LOG = logging.getLogger(log_name)
34+
ccos.log.reset_handler()
3535

3636

3737
def set_up_repo(git_working_dir):
3838
if not os.path.isdir(git_working_dir):
39-
logger.log(logging.INFO, "Cloning repo...")
39+
LOG.info("Cloning repo...")
4040
repo = git.Repo.clone_from(
4141
url=GITHUB_REPO_URL_WITH_CREDENTIALS, to_path=git_working_dir
4242
)
4343
else:
44-
logger.log(logging.INFO, "Setting up repo...")
44+
LOG.info("Setting up repo...")
4545
repo = git.Repo(git_working_dir)
4646
origin = repo.remotes.origin
47-
logger.log(logging.INFO, "Pulling latest code...")
47+
LOG.info("Pulling latest code...")
4848
origin.pull()
4949

5050

5151
def set_up_git_user():
52-
logger.log(logging.INFO, "Setting up git user...")
52+
LOG.info("Setting up git user...")
5353
os.environ["GIT_AUTHOR_NAME"] = GIT_USER_NAME
5454
os.environ["GIT_AUTHOR_EMAIL"] = GIT_USER_EMAIL
5555
os.environ["GIT_COMMITTER_NAME"] = GIT_USER_NAME
5656
os.environ["GIT_COMMITTER_EMAIL"] = GIT_USER_EMAIL
5757

5858

5959
def generate_json_file(git_working_dir, data, filename):
60-
logger.log(logging.INFO, "Generating JSON file...")
60+
LOG.info("Generating JSON file...")
6161
json_filename = os.path.join(git_working_dir, JSON_FILE_DIR, filename)
6262
with open(json_filename, "w") as json_file:
6363
json.dump(data, json_file, sort_keys=True, indent=4)
@@ -71,14 +71,14 @@ def commit_and_push_changes(git_working_dir, json_filename):
7171
repo.index.add(items=f"{json_filename}")
7272
repo.index.commit(message="Syncing new data changes.")
7373
origin = repo.remotes.origin
74-
logger.log(logging.INFO, "Pushing latest code...")
74+
LOG.info("Pushing latest code...")
7575
origin.push()
7676
else:
77-
logger.log(logging.INFO, "No changes to push...")
77+
LOG.info("No changes to push...")
7878

7979

8080
def push_data(data, filename):
81-
with tempfile.TemporaryDirectory() as temp_dir:
81+
with TemporaryDirectory() as temp_dir:
8282
git_working_dir = os.path.join(temp_dir, GITHUB_REPO_NAME)
8383
set_up_repo(git_working_dir)
8484
set_up_git_user()

ccos/gh_utils.py

+22-15
Original file line numberDiff line numberDiff line change
@@ -10,41 +10,48 @@
1010
from github.GithubException import BadCredentialsException
1111

1212
# First-party/Local
13-
from ccos import log
13+
import ccos.log
1414

1515
GITHUB_ORGANIZATION = "creativecommons"
16-
GITHUB_USERNAME = "cc-creativecommons-github-io-bot"
17-
GITHUB_TOKEN = None
16+
GITHUB_USERNAME_DEFAULT = "cc-creativecommons-github-io-bot"
1817

1918
log_name = os.path.basename(os.path.splitext(inspect.stack()[-1].filename)[0])
20-
logger = logging.getLogger(log_name)
21-
log.reset_handler()
19+
LOG = logging.getLogger(log_name)
20+
ccos.log.reset_handler()
2221

2322

24-
def set_up_github_client():
25-
global GITHUB_TOKEN
23+
def get_credentials():
2624
try:
27-
GITHUB_TOKEN = os.environ["ADMIN_GITHUB_TOKEN"]
25+
github_token = os.environ["ADMIN_GITHUB_TOKEN"]
2826
except KeyError:
29-
logger.critical("missing ADMIN_GITHUB_TOKEN environment variable")
27+
LOG.critical("missing ADMIN_GITHUB_TOKEN environment variable")
3028
sys.exit(1)
31-
logger.log(logging.INFO, "Setting up GitHub client...")
32-
github_client = Github(GITHUB_TOKEN)
33-
logger.log(log.SUCCESS, "done.")
29+
try:
30+
github_username = os.environ["ADMIN_GITHUB_USERNAME"]
31+
except KeyError:
32+
github_username = GITHUB_USERNAME_DEFAULT
33+
return github_username, github_token
34+
35+
36+
def set_up_github_client():
37+
_, github_token = get_credentials()
38+
LOG.info("Setting up GitHub client...")
39+
github_client = Github(github_token)
40+
LOG.log(ccos.log.SUCCESS, "done.")
3441
return github_client
3542

3643

3744
def get_cc_organization(github_client):
38-
logger.log(logging.INFO, "Getting CC's GitHub organization...")
45+
LOG.info("Getting CC's GitHub organization...")
3946
try:
4047
cc = github_client.get_organization(GITHUB_ORGANIZATION)
4148
except BadCredentialsException as e:
42-
logger.critical(
49+
LOG.critical(
4350
f"{e.status} {e.data['message']} (see"
4451
f" {e.data['documentation_url']})"
4552
)
4653
sys.exit(1)
47-
logger.log(log.SUCCESS, "done.")
54+
LOG.log(ccos.log.SUCCESS, "done.")
4855
return cc
4956

5057

ccos/log.py

+13-7
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ class IndentFormatter(logging.Formatter):
1818
logging.WARNING: 33, # yellow
1919
SUCCESS: 32, # green
2020
logging.INFO: 34, # blue
21+
logging.DEBUG: 35, # magenta
2122
}
2223

2324
@staticmethod
@@ -64,10 +65,13 @@ def update_format(self, record):
6465
"%(asctime)s │ "
6566
f"{prefix}{color}%(levelname)-8s{prefix}{reset} │ "
6667
)
67-
self._style._fmt += (
68-
f"%(indent)s{prefix}{bold}%(function)s{prefix}{reset}: "
69-
"%(message)s"
70-
)
68+
if hasattr(record, "function"):
69+
self._style._fmt += (
70+
f"%(indent)s{prefix}{bold}%(function)s{prefix}{reset}: "
71+
"%(message)s"
72+
)
73+
else:
74+
self._style._fmt += "%(indent)s%(message)s"
7175

7276
def format(self, record):
7377
"""
@@ -81,19 +85,21 @@ def format(self, record):
8185
self.baseline = depth
8286
if self.cut is None:
8387
filenames = map(lambda x: x.filename, stack)
84-
self.cut = IndentFormatter.identify_cut(filenames)
88+
self.cut = self.identify_cut(filenames)
8589

8690
# Inject custom information into the record
8791
record.indent = ". " * (depth - self.baseline + self.manual_push)
88-
record.function = stack[self.cut].function
92+
if depth > self.cut:
93+
record.function = stack[self.cut].function
8994

9095
# Format the record using custom information
9196
self.update_format(record)
9297
out = super().format(record)
9398

9499
# Remove custom information from the record
95100
del record.indent
96-
del record.function
101+
if hasattr(record, "function"):
102+
del record.function
97103

98104
return out
99105

0 commit comments

Comments
 (0)