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

Conversation

PokkaKiyo
Copy link

@PokkaKiyo PokkaKiyo commented Nov 24, 2024

Type of changes

  • Bug fix
  • New feature
  • Documentation / docstrings
  • Tests
  • Other

Checklist

  • I've run the latest black with default args on new code.
  • I've updated CHANGELOG.md and CONTRIBUTORS.md where appropriate.
  • I've added tests for new code.
  • I accept that @willmcgugan may be pedantic in the code review.

Description

Add option to pass a timezone into RichHandler for log timestamps.

Currently, the timestamp produced by RichHandler ignores the "%z" field if it is passed into the dateformat, likely because the datetime object created in RichHandler.render is timezone-naive. We can make it timezone-aware by passing in the expected timezone when calling datetime.fromtimestamp on the log message's timestamp.

The current alternative to doing this would be something like

import logging
from datetime import UTC, datetime

from rich.logging import RichHandler
from rich.text import Text

logging.basicConfig(
    level="NOTSET",
    format="%(message)s",
    handlers=[
        RichHandler(
            rich_tracebacks=True,
            tracebacks_show_locals=True,
            log_time_format=lambda dt: Text(
                datetime.fromtimestamp(dt.timestamp(), tz=UTC).strftime("%Y-%m-%dT%H:%M:%S%z")
            ),
        )
    ],
)
logging.debug("hello")  # 2024-11-24T08:53:00+0000 DEBUG    hello 

@PokkaKiyo PokkaKiyo marked this pull request as ready for review November 24, 2024 08:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant