Skip to content

Commit

Permalink
detect tty
Browse files Browse the repository at this point in the history
  • Loading branch information
rkaminsk committed Feb 23, 2024
1 parent fc4dd6c commit c2ba3d3
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/fillname/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def main() -> None:
"""
parser = get_parser()
args = parser.parse_args()
configure_logging(sys.stderr, args.log)
configure_logging(sys.stderr, args.log, sys.stderr.isatty())

log = get_logger("main")
log.info("info")
Expand Down
9 changes: 6 additions & 3 deletions src/fillname/utils/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,20 @@ def filter(self, record: logging.LogRecord) -> bool:
return record.levelno == self.passlevel


def configure_logging(stream: TextIO, level: int) -> None:
def configure_logging(stream: TextIO, level: int, use_color: bool) -> None:
"""
Configure application logging.
"""
log_message_str = "{}%(levelname)s:{} - %(message)s{}"
def format_str(color: str) -> str:
if use_color:
return f"{COLORS[color]}%(levelname)s:{COLORS['GREY']} - %(message)s{COLORS['NORMAL']}"
return "%(levelname)s: - %(message)s" # nocoverage

def make_handler(level: int, color: str) -> "logging.StreamHandler[TextIO]":
handler = logging.StreamHandler(stream)
handler.addFilter(SingleLevelFilter(level, False))
handler.setLevel(level)
formatter = logging.Formatter(log_message_str.format(COLORS[color], COLORS["GREY"], COLORS["NORMAL"]))
formatter = logging.Formatter(format_str(color))
handler.setFormatter(formatter)
return handler

Expand Down
2 changes: 1 addition & 1 deletion tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def test_logger(self) -> None:
Test the logger.
"""
sio = StringIO()
configure_logging(sio, logging.INFO)
configure_logging(sio, logging.INFO, True)
log = get_logger("main")
log.info("test123")
self.assertRegex(sio.getvalue(), "test123")
Expand Down

0 comments on commit c2ba3d3

Please sign in to comment.