Skip to content

Commit 57c8a8e

Browse files
fix: upload log file only when not dry-run
1 parent 0fa2cff commit 57c8a8e

File tree

1 file changed

+53
-28
lines changed

1 file changed

+53
-28
lines changed

src/gentroutils/commands/utils.py

Lines changed: 53 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import time
77
from functools import wraps
88
from pathlib import Path
9+
from tempfile import NamedTemporaryFile
910
from urllib.parse import urlparse
1011

1112
import click
@@ -39,33 +40,47 @@ def set_log_file(ctx: click.Context, param: click.Option, log_file: str) -> str:
3940
return ""
4041
logger.info("Extracting log file from the %s", param)
4142
upload_to_gcp = False
43+
4244
if "://" in log_file:
4345
upload_to_gcp = True
46+
ctx.obj["upload_to_gcp"] = upload_to_gcp
47+
4448
if upload_to_gcp:
4549
parsed_uri = urlparse(log_file)
46-
ctx.obj["gcp_log_file"] = log_file
4750
if parsed_uri.scheme != "gs":
4851
raise click.BadParameter("Only GCS is supported for logging upload")
49-
log_file = parsed_uri.path.strip("/")
50-
ctx.obj["local_log_file"] = log_file
51-
ctx.obj["upload_to_gcp"] = upload_to_gcp
52-
53-
local_file = Path(log_file)
54-
if local_file.exists() and local_file.is_dir():
55-
raise click.BadParameter("Log file is a directory")
56-
if local_file.exists() and local_file.is_file():
57-
local_file.unlink()
58-
if not local_file.exists():
59-
local_file.touch()
60-
logger.info("Logging to %s", local_file)
61-
handler = logging.FileHandler(local_file)
62-
formatter = logging.Formatter(
63-
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
64-
)
65-
handler.setFormatter(formatter)
66-
handler.setLevel(logging.DEBUG)
67-
logger.addHandler(handler)
68-
return str(local_file)
52+
tmp_file = NamedTemporaryFile(delete=False)
53+
logger.info("Logging to temporary file %s", tmp_file.name)
54+
handler = logging.FileHandler(tmp_file.name)
55+
formatter = logging.Formatter(
56+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
57+
)
58+
handler.setFormatter(formatter)
59+
handler.setLevel(logging.DEBUG)
60+
logger.addHandler(handler)
61+
ctx.obj["local_log_file"] = tmp_file.name
62+
ctx.obj["local_log_file_obj"] = tmp_file
63+
ctx.obj["gcp_log_file"] = log_file
64+
return tmp_file.name
65+
66+
else:
67+
local_file = Path(log_file)
68+
if local_file.exists() and local_file.is_dir():
69+
raise click.BadParameter("Log file is a directory")
70+
if local_file.exists() and local_file.is_file():
71+
local_file.unlink()
72+
if not local_file.exists():
73+
local_file.parent.mkdir(parents=True, exist_ok=True)
74+
local_file.touch()
75+
logger.info("Logging to %s", local_file)
76+
handler = logging.FileHandler(local_file)
77+
formatter = logging.Formatter(
78+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
79+
)
80+
handler.setFormatter(formatter)
81+
handler.setLevel(logging.DEBUG)
82+
logger.addHandler(handler)
83+
return str(local_file)
6984

7085

7186
def teardown_cli(ctx: click.Context) -> None:
@@ -80,13 +95,23 @@ def teardown_cli(ctx: click.Context) -> None:
8095
if "upload_to_gcp" in ctx.obj and ctx.obj["upload_to_gcp"]:
8196
gcp_file = ctx.obj["gcp_log_file"]
8297
local_file = ctx.obj["local_log_file"]
83-
client = storage.Client()
84-
bucket_name = urlparse(gcp_file).netloc
85-
bucket = client.bucket(bucket_name=bucket_name)
86-
blob = bucket.blob(Path(local_file).name)
87-
logger.info("Uploading %s to %s", local_file, gcp_file)
88-
blob.upload_from_filename(local_file)
89-
Path(local_file).unlink()
98+
with open(local_file, "r") as f:
99+
content = f.read()
100+
try:
101+
client = storage.Client()
102+
bucket_name = urlparse(gcp_file).netloc
103+
bucket = client.bucket(bucket_name=bucket_name)
104+
file_name = urlparse(gcp_file).path.lstrip("/")
105+
blob = bucket.blob(file_name)
106+
logger.info("Uploading %s to %s", local_file, gcp_file)
107+
if ctx.obj["dry_run"]:
108+
logger.info("Dry run, skipping the upload of the log file")
109+
else:
110+
blob.upload_from_string(content)
111+
ctx.obj["local_log_file_obj"].close()
112+
except Exception as e:
113+
msg = f"Failed to upload log file to GCP {e}"
114+
logger.error(click.style(msg, fg="red"))
90115
logger.info(
91116
"Finished, elapsed time %s seconds", time.time() - ctx.obj["execution_start"]
92117
)

0 commit comments

Comments
 (0)