log.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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. import functools
  18. import inspect
  19. import json
  20. import logging
  21. import textwrap
  22. from abc import ABC, abstractmethod
  23. from datetime import datetime
  24. from typing import Any, cast, Type
  25. from flask import current_app, g, request
  26. class AbstractEventLogger(ABC):
  27. @abstractmethod
  28. def log(self, user_id, action, *args, **kwargs):
  29. pass
  30. def log_this(self, f):
  31. @functools.wraps(f)
  32. def wrapper(*args, **kwargs):
  33. user_id = None
  34. if g.user:
  35. user_id = g.user.get_id()
  36. d = request.form.to_dict() or {}
  37. # request parameters can overwrite post body
  38. request_params = request.args.to_dict()
  39. d.update(request_params)
  40. d.update(kwargs)
  41. slice_id = d.get("slice_id")
  42. dashboard_id = d.get("dashboard_id")
  43. try:
  44. slice_id = int(
  45. slice_id or json.loads(d.get("form_data")).get("slice_id")
  46. )
  47. except (ValueError, TypeError):
  48. slice_id = 0
  49. self.stats_logger.incr(f.__name__)
  50. start_dttm = datetime.now()
  51. value = f(*args, **kwargs)
  52. duration_ms = (datetime.now() - start_dttm).total_seconds() * 1000
  53. # bulk insert
  54. try:
  55. explode_by = d.get("explode")
  56. records = json.loads(d.get(explode_by))
  57. except Exception: # pylint: disable=broad-except
  58. records = [d]
  59. referrer = request.referrer[:1000] if request.referrer else None
  60. self.log(
  61. user_id,
  62. f.__name__,
  63. records=records,
  64. dashboard_id=dashboard_id,
  65. slice_id=slice_id,
  66. duration_ms=duration_ms,
  67. referrer=referrer,
  68. )
  69. return value
  70. return wrapper
  71. @property
  72. def stats_logger(self):
  73. return current_app.config["STATS_LOGGER"]
  74. def get_event_logger_from_cfg_value(cfg_value: object) -> AbstractEventLogger:
  75. """
  76. This function implements the deprecation of assignment
  77. of class objects to EVENT_LOGGER configuration, and validates
  78. type of configured loggers.
  79. The motivation for this method is to gracefully deprecate the ability to configure
  80. EVENT_LOGGER with a class type, in favor of preconfigured instances which may have
  81. required construction-time injection of proprietary or locally-defined dependencies.
  82. :param cfg_value: The configured EVENT_LOGGER value to be validated
  83. :return: if cfg_value is a class type, will return a new instance created using a
  84. default con
  85. """
  86. result: Any = cfg_value
  87. if inspect.isclass(cfg_value):
  88. logging.warning(
  89. textwrap.dedent(
  90. """
  91. In superset private config, EVENT_LOGGER has been assigned a class
  92. object. In order to accomodate pre-configured instances without a
  93. default constructor, assignment of a class is deprecated and may no
  94. longer work at some point in the future. Please assign an object
  95. instance of a type that implements
  96. superset.utils.log.AbstractEventLogger.
  97. """
  98. )
  99. )
  100. event_logger_type = cast(Type, cfg_value)
  101. result = event_logger_type()
  102. # Verify that we have a valid logger impl
  103. if not isinstance(result, AbstractEventLogger):
  104. raise TypeError(
  105. "EVENT_LOGGER must be configured with a concrete instance"
  106. "of superset.utils.log.AbstractEventLogger."
  107. )
  108. logging.info(f"Configured event logger of type {type(result)}")
  109. return cast(AbstractEventLogger, result)
  110. class DBEventLogger(AbstractEventLogger):
  111. def log(self, user_id, action, *args, **kwargs): # pylint: disable=too-many-locals
  112. from superset.models.core import Log
  113. records = kwargs.get("records", list())
  114. dashboard_id = kwargs.get("dashboard_id")
  115. slice_id = kwargs.get("slice_id")
  116. duration_ms = kwargs.get("duration_ms")
  117. referrer = kwargs.get("referrer")
  118. logs = list()
  119. for record in records:
  120. try:
  121. json_string = json.dumps(record)
  122. except Exception: # pylint: disable=broad-except
  123. json_string = None
  124. log = Log(
  125. action=action,
  126. json=json_string,
  127. dashboard_id=dashboard_id,
  128. slice_id=slice_id,
  129. duration_ms=duration_ms,
  130. referrer=referrer,
  131. user_id=user_id,
  132. )
  133. logs.append(log)
  134. sesh = current_app.appbuilder.get_session
  135. sesh.bulk_save_objects(logs)
  136. sesh.commit()