formatter.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/env python
  2. # Licensed to Cloudera, Inc. under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. Cloudera, Inc. licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import logging
  18. import os
  19. from pytz import UnknownTimeZoneError, datetime, timezone
  20. class Formatter(logging.Formatter):
  21. def formatTime(self, record, datefmt=None):
  22. try:
  23. tz = timezone(os.environ['TZ'])
  24. except (KeyError, UnknownTimeZoneError):
  25. tz = None
  26. try:
  27. ct = datetime.datetime.fromtimestamp(record.created, tz=tz)
  28. except (OverflowError, TypeError, ValueError):
  29. # Fallback to original.
  30. return super(Formatter, self).formatTime(record, datefmt=datefmt)
  31. if datefmt:
  32. s = ct.strftime(datefmt)
  33. else:
  34. t = ct.strftime("%Y-%m-%d %H:%M:%S")
  35. s = "%s,%03d" % (t, record.msecs)
  36. return s
  37. class MessageOnlyFormatter(logging.Formatter):
  38. def formatTime(self, record, datefmt=None):
  39. return ''
  40. def format(self, record):
  41. return record.getMessage()