timezone_aware.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. from __future__ import annotations
  18. import logging
  19. from airflow.utils import timezone
  20. class TimezoneAware(logging.Formatter):
  21. """
  22. Override time-formatting methods to include UTC offset.
  23. Since Airflow parses the logs to perform time conversion, UTC offset is
  24. critical information. This formatter ensures ``%(asctime)s`` is formatted
  25. containing the offset in ISO 8601, e.g. ``2022-06-12T13:00:00.123+0000``.
  26. """
  27. default_time_format = "%Y-%m-%dT%H:%M:%S"
  28. default_msec_format = "%s.%03d"
  29. default_tz_format = "%z"
  30. def formatTime(self, record, datefmt=None):
  31. """
  32. Format time in record.
  33. This returns the creation time of the specified LogRecord in ISO 8601
  34. date and time format in the local time zone.
  35. """
  36. dt = timezone.from_timestamp(record.created, tz="local")
  37. s = dt.strftime(datefmt or self.default_time_format)
  38. if self.default_msec_format:
  39. s = self.default_msec_format % (s, record.msecs)
  40. if self.default_tz_format:
  41. s += dt.strftime(self.default_tz_format)
  42. return s