Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to pass a timezone into richhandler for log timestamps #3574

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- Allow a `log_time_zone` argument to be passed to `RichHandler`


## [13.9.4] - 2024-11-01

Expand Down
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ The following people have contributed to the development of Rich:
- [Nicolas Simonds](https://github.com/0xDEC0DE)
- [Aaron Stephens](https://github.com/aaronst)
- [Karolina Surma](https://github.com/befeleme)
- [Wei Jie Tan](https://github.com/PokkaKiyo)
- [Gabriele N. Tornetta](https://github.com/p403n1x87)
- [Nils Vu](https://github.com/nilsvu)
- [Arian Mollik Wasi](https://github.com/wasi-master)
Expand Down
7 changes: 5 additions & 2 deletions rich/logging.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logging
from datetime import datetime
from datetime import datetime, tzinfo
from logging import Handler, LogRecord
from pathlib import Path
from types import ModuleType
Expand Down Expand Up @@ -47,6 +47,7 @@ class RichHandler(Handler):
Defaults to 10.
locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%x %X] ".
log_time_zone (datetime.tzinfo, optional): The timezone used to convert log message timestamps into "aware" datetime objects. Defaults to None.
keywords (List[str], optional): List of words to highlight instead of ``RichHandler.KEYWORDS``.
"""

Expand Down Expand Up @@ -86,6 +87,7 @@ def __init__(
locals_max_length: int = 10,
locals_max_string: int = 80,
log_time_format: Union[str, FormatTimeCallable] = "[%x %X]",
log_time_zone: Optional[tzinfo] = None,
keywords: Optional[List[str]] = None,
) -> None:
super().__init__(level=level)
Expand All @@ -112,6 +114,7 @@ def __init__(
self.tracebacks_code_width = tracebacks_code_width
self.locals_max_length = locals_max_length
self.locals_max_string = locals_max_string
self.log_time_zone = log_time_zone
self.keywords = keywords

def get_level_text(self, record: LogRecord) -> Text:
Expand Down Expand Up @@ -224,7 +227,7 @@ def render(
path = Path(record.pathname).name
level = self.get_level_text(record)
time_format = None if self.formatter is None else self.formatter.datefmt
log_time = datetime.fromtimestamp(record.created)
log_time = datetime.fromtimestamp(record.created, tz=self.log_time_zone)

log_renderable = self._log_render(
self.console,
Expand Down
47 changes: 47 additions & 0 deletions tests/test_logging.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import datetime
import io
import os
import logging
from typing import Optional
from unittest import mock

import pytest

Expand Down Expand Up @@ -162,6 +164,51 @@ def test_markup_and_highlight():
assert log_message in render_plain


@pytest.mark.parametrize(
["timezone", "expected_timestamp"],
[
(
datetime.UTC,
"2025-01-01T00:00:00+0000",
),
(
datetime.timezone(-datetime.timedelta(hours=1)),
"2024-12-31T23:00:00-0100",
),
(
datetime.timezone(datetime.timedelta(hours=2, minutes=30)),
"2025-01-01T02:30:00+0230",
),
],
)
@mock.patch("time.time", lambda: 1735689600)
def test_timestamp(timezone, expected_timestamp):
console = Console(
file=io.StringIO(),
force_terminal=True,
width=140,
color_system=None,
_environ={},
)
handler_with_tracebacks = RichHandler(
console=console,
enable_link_path=False,
rich_tracebacks=True,
log_time_zone=timezone,
)
formatter = logging.Formatter(
"FORMATTER %(message)s", datefmt=r"%Y-%m-%dT%H:%M:%S%z"
)
handler_with_tracebacks.setFormatter(formatter)
log.addHandler(handler_with_tracebacks)
log.error("foo")

render = handler_with_tracebacks.console.file.getvalue()

assert "FORMATTER foo" in render
assert expected_timestamp in render


if __name__ == "__main__":
render = make_log()
print(render)
Expand Down