Skip to content

Commit 2fd6721

Browse files
authored
feat: add ability to configure logging dir (#2266)
1 parent b8ea6de commit 2fd6721

File tree

6 files changed

+136
-40
lines changed

6 files changed

+136
-40
lines changed

sqlmesh/__init__.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import typing as t
1212
from datetime import datetime
1313
from enum import Enum
14+
from pathlib import Path
1415

1516
from sqlmesh.core.dialect import extend_sqlglot
1617

@@ -93,7 +94,7 @@ def is_notebook(self) -> bool:
9394

9495

9596
LOG_FORMAT = "%(asctime)s - %(threadName)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
96-
LOG_PREFIX = "logs/sqlmesh_"
97+
LOG_FILENAME_PREFIX = "sqlmesh_"
9798

9899

99100
# SO: https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output
@@ -126,6 +127,7 @@ def configure_logging(
126127
write_to_stdout: bool = False,
127128
write_to_file: bool = True,
128129
log_limit: int = c.DEFAULT_LOG_LIMIT,
130+
log_file_dir: t.Optional[t.Union[str, Path]] = None,
129131
) -> None:
130132
logger = logging.getLogger()
131133
debug = force_debug or debug_mode_enabled()
@@ -141,9 +143,11 @@ def configure_logging(
141143
)
142144
logger.addHandler(stdout_handler)
143145

146+
log_file_dir = log_file_dir or c.DEFAULT_LOG_FILE_DIR
147+
log_path_prefix = Path(log_file_dir) / LOG_FILENAME_PREFIX
144148
if write_to_file:
145-
os.makedirs("logs", exist_ok=True)
146-
filename = f"{LOG_PREFIX}{datetime.now().strftime('%Y_%m_%d_%H_%M_%S')}.log"
149+
os.makedirs(str(log_file_dir), exist_ok=True)
150+
filename = f"{log_path_prefix}{datetime.now().strftime('%Y_%m_%d_%H_%M_%S')}.log"
147151
file_handler = logging.FileHandler(filename, mode="w", encoding="utf-8")
148152
# the log files should always log at least info so that users will always have
149153
# minimal info for debugging even if they specify "ignore_warnings"
@@ -152,7 +156,7 @@ def configure_logging(
152156
logger.addHandler(file_handler)
153157

154158
if log_limit > 0:
155-
for path in list(sorted(glob.glob(f"{LOG_PREFIX}*.log"), reverse=True))[log_limit:]:
159+
for path in list(sorted(glob.glob(f"{log_path_prefix}*.log"), reverse=True))[log_limit:]:
156160
os.remove(path)
157161

158162
if debug:

sqlmesh/cli/main.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,11 @@ def _sqlmesh_version() -> str:
5252
is_flag=True,
5353
help="Display logs in stdout.",
5454
)
55+
@click.option(
56+
"--log-file-dir",
57+
type=str,
58+
help="The directory to write log files to.",
59+
)
5560
@click.pass_context
5661
@error_handler
5762
def cli(
@@ -62,6 +67,7 @@ def cli(
6267
ignore_warnings: bool = False,
6368
debug: bool = False,
6469
log_to_stdout: bool = False,
70+
log_file_dir: t.Optional[str] = None,
6571
) -> None:
6672
"""SQLMesh command line tool."""
6773
if "--help" in sys.argv:
@@ -79,7 +85,9 @@ def cli(
7985

8086
configs = load_configs(config, Context.CONFIG_TYPE, paths)
8187
log_limit = list(configs.values())[0].log_limit
82-
configure_logging(debug, ignore_warnings, log_to_stdout, log_limit=log_limit)
88+
configure_logging(
89+
debug, ignore_warnings, log_to_stdout, log_limit=log_limit, log_file_dir=log_file_dir
90+
)
8391

8492
try:
8593
context = Context(

sqlmesh/core/constants.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@
3636
DEFAULT_LOG_LIMIT = 20
3737
"""The default number of logs to keep."""
3838

39+
DEFAULT_LOG_FILE_DIR = "logs"
40+
"""The default directory for log files."""
41+
3942
AUDITS = "audits"
4043
MACROS = "macros"
4144
METRICS = "metrics"

sqlmesh/magics.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ def _shell(self) -> t.Any:
9191
@argument("--gateway", type=str, help="The name of the gateway.")
9292
@argument("--ignore-warnings", action="store_true", help="Ignore warnings.")
9393
@argument("--debug", action="store_true", help="Enable debug mode.")
94+
@argument("--log-file-dir", type=str, help="The directory to write the log file to.")
9495
@line_magic
9596
def context(self, line: str) -> None:
9697
"""Sets the context in the user namespace."""
@@ -99,7 +100,9 @@ def context(self, line: str) -> None:
99100
args = parse_argstring(self.context, line)
100101
configs = load_configs(args.config, Context.CONFIG_TYPE, args.paths)
101102
log_limit = list(configs.values())[0].log_limit
102-
configure_logging(args.debug, args.ignore_warnings, log_limit=log_limit)
103+
configure_logging(
104+
args.debug, args.ignore_warnings, log_limit=log_limit, log_file_dir=args.log_file_dir
105+
)
103106
try:
104107
context = Context(paths=args.paths, config=configs, gateway=args.gateway)
105108
self._shell.user_ns["context"] = context

0 commit comments

Comments
 (0)