diff --git a/.env.example b/.env.example
index 0a927c6787..446fef003f 100644
--- a/.env.example
+++ b/.env.example
@@ -106,6 +106,7 @@ DATABASE_NAME=baserow
# BASEROW_JOBS_FRONTEND_POLLING_TIMEOUT_MS=
# BASEROW_PLUGIN_DIR=
# BASEROW_MAX_SNAPSHOTS_PER_GROUP=
+# BASEROW_ENABLE_OTEL=
# BASEROW_DISABLE_PUBLIC_URL_CHECK=
# DOWNLOAD_FILE_VIA_XHR=
diff --git a/backend/docker/docker-entrypoint.sh b/backend/docker/docker-entrypoint.sh
index 7187928243..aa9f18e55f 100755
--- a/backend/docker/docker-entrypoint.sh
+++ b/backend/docker/docker-entrypoint.sh
@@ -6,6 +6,8 @@ set -euo pipefail
# ENVIRONMENT VARIABLES USED DIRECTLY BY THIS ENTRYPOINT
# ======================================================
+export BASEROW_VERSION="1.14.0"
+
# Used by docker-entrypoint.sh to start the dev server
# If not configured you'll receive this: CommandError: "0.0.0.0:" is not a valid port number or address:port pair.
BASEROW_BACKEND_PORT="${BASEROW_BACKEND_PORT:-8000}"
@@ -155,7 +157,7 @@ run_setup_commands_if_configured(){
startup_plugin_setup
if [ "$MIGRATE_ON_STARTUP" = "true" ] ; then
echo "python /baserow/backend/src/baserow/manage.py migrate"
- python /baserow/backend/src/baserow/manage.py migrate
+ OTEL_SERVICE_NAME=backend-migrate python /baserow/backend/src/baserow/manage.py migrate
fi
}
@@ -216,6 +218,24 @@ run_backend_server(){
"${@:2}"
}
+setup_otel_vars(){
+ # These key value pairs will be exported on every log/metric/trace by any otel
+ # exporters running in subprocesses launched by this script.
+ EXTRA_OTEL_RESOURCE_ATTRIBUTES="service.namespace=Baserow,"
+ EXTRA_OTEL_RESOURCE_ATTRIBUTES+="service.version=${BASEROW_VERSION},"
+ EXTRA_OTEL_RESOURCE_ATTRIBUTES+="deployment.environment=${BASEROW_DEPLOYMENT_ENV:-unknown}"
+
+ if [[ -n "${OTEL_RESOURCE_ATTRIBUTES:-}" ]]; then
+ # If the container has been launched with some extra otel attributes, make sure not
+ # to override them with our Baserow specific ones.
+ OTEL_RESOURCE_ATTRIBUTES="${EXTRA_OTEL_RESOURCE_ATTRIBUTES},${OTEL_RESOURCE_ATTRIBUTES}"
+ else
+ OTEL_RESOURCE_ATTRIBUTES="$EXTRA_OTEL_RESOURCE_ATTRIBUTES"
+ fi
+ export OTEL_RESOURCE_ATTRIBUTES
+ echo "OTEL_RESOURCE_ATTRIBUTES=$OTEL_RESOURCE_ATTRIBUTES"
+}
+
# ======================================================
# COMMANDS
# ======================================================
@@ -229,24 +249,30 @@ fi
source /baserow/venv/bin/activate
source /baserow/plugins/utils.sh
+setup_otel_vars
+
case "$1" in
django-dev)
wait_for_postgres
run_setup_commands_if_configured
echo "Running Development Server on 0.0.0.0:${BASEROW_BACKEND_PORT}"
echo "Press CTRL-p CTRL-q to close this session without stopping the container."
+ export OTEL_SERVICE_NAME=backend-dev
attachable_exec python /baserow/backend/src/baserow/manage.py runserver "${BASEROW_BACKEND_BIND_ADDRESS:-0.0.0.0}:${BASEROW_BACKEND_PORT}"
;;
django-dev-no-attach)
wait_for_postgres
run_setup_commands_if_configured
echo "Running Development Server on 0.0.0.0:${BASEROW_BACKEND_PORT}"
+ export OTEL_SERVICE_NAME=backend-dev
python /baserow/backend/src/baserow/manage.py runserver "${BASEROW_BACKEND_BIND_ADDRESS:-0.0.0.0}:${BASEROW_BACKEND_PORT}"
;;
gunicorn)
+ export OTEL_SERVICE_NAME="backend-asgi"
run_backend_server asgi "${@:2}"
;;
gunicorn-wsgi)
+ export OTEL_SERVICE_NAME="backend-wsgi"
run_backend_server wsgi "${@:2}"
;;
backend-healthcheck)
@@ -264,6 +290,7 @@ case "$1" in
exec /bin/bash -c "${@:2}"
;;
manage)
+ export OTEL_SERVICE_NAME=backend-manage
exec python3 /baserow/backend/src/baserow/manage.py "${@:2}"
;;
python)
@@ -271,11 +298,12 @@ case "$1" in
;;
setup)
echo "python3 /baserow/backend/src/baserow/manage.py migrate"
- DONT_UPDATE_FORMULAS_AFTER_MIGRATION=yes python3 /baserow/backend/src/baserow/manage.py migrate
+ OTEL_SERVICE_NAME=backend-migrate DONT_UPDATE_FORMULAS_AFTER_MIGRATION=yes python3 /baserow/backend/src/baserow/manage.py migrate
echo "python3 /baserow/backend/src/baserow/manage.py update_formulas"
- python3 /baserow/backend/src/baserow/manage.py update_formulas
+ OTEL_SERVICE_NAME=backend-update-formulas python3 /baserow/backend/src/baserow/manage.py update_formulas
;;
shell)
+ export OTEL_SERVICE_NAME=backend-shell
exec python3 /baserow/backend/src/baserow/manage.py shell
;;
lint-shell)
@@ -292,9 +320,11 @@ case "$1" in
;;
celery-worker)
if [[ -n "${BASEROW_RUN_MINIMAL}" && $BASEROW_AMOUNT_OF_WORKERS == "1" ]]; then
+ export OTEL_SERVICE_NAME="celery-worker-combined"
echo "Starting combined celery and export worker..."
start_celery_worker -Q celery,export -n default-worker@%h "${@:2}"
else
+ export OTEL_SERVICE_NAME="celery-worker"
start_celery_worker -Q celery -n default-worker@%h "${@:2}"
fi
;;
@@ -308,6 +338,7 @@ case "$1" in
"to reduce memory usage"
while true; do sleep 2073600; done
else
+ export OTEL_SERVICE_NAME="celery-exportworker"
start_celery_worker -Q export -n export-worker@%h "${@:2}"
fi
;;
@@ -322,6 +353,7 @@ case "$1" in
echo "Sleeping for $BASEROW_CELERY_BEAT_STARTUP_DELAY before starting beat to prevent "\
"startup errors."
sleep "$BASEROW_CELERY_BEAT_STARTUP_DELAY"
+ export OTEL_SERVICE_NAME="celery-beat"
exec celery -A baserow beat -l "${BASEROW_CELERY_BEAT_DEBUG_LEVEL}" -S redbeat.RedBeatScheduler "${@:2}"
;;
watch-py)
diff --git a/backend/pytest.ini b/backend/pytest.ini
index 76cae44a3e..6d6182744f 100644
--- a/backend/pytest.ini
+++ b/backend/pytest.ini
@@ -6,6 +6,7 @@ env =
BASEROW_JWT_SIGNING_KEY = test
DJANGO_SETTINGS_MODULE = baserow.config.settings.test
FEATURE_FLAGS = *
+ BASEROW_ENABLE_OTEL =
testpaths =
tests
../premium/backend/tests
diff --git a/backend/requirements/base.in b/backend/requirements/base.in
index 9aa11703f2..eac90a9ea8 100644
--- a/backend/requirements/base.in
+++ b/backend/requirements/base.in
@@ -36,5 +36,25 @@ redis==4.1.4
pysaml2==7.2.1
validators==0.20.0
requests-oauthlib==1.3.1
+opentelemetry-api==1.15.0
+opentelemetry-exporter-otlp-proto-http==1.15.0
+opentelemetry-instrumentation==0.36b0
+opentelemetry-instrumentation-django==0.36b0
+opentelemetry-instrumentation-aiohttp-client==0.36b0
+opentelemetry-instrumentation-asgi==0.36b0
+opentelemetry-instrumentation-botocore==0.36b0
+opentelemetry-instrumentation-celery==0.36b0
+opentelemetry-instrumentation-dbapi==0.36b0
+opentelemetry-instrumentation-grpc==0.36b0
+opentelemetry-instrumentation-logging==0.36b0
+opentelemetry-instrumentation-psycopg2==0.36b0
+opentelemetry-instrumentation-redis==0.36b0
+opentelemetry-instrumentation-requests==0.36b0
+opentelemetry-instrumentation-wsgi==0.36b0
+opentelemetry-proto==1.15.0
+opentelemetry-sdk==1.15.0
+opentelemetry-semantic-conventions==0.36b0
+opentelemetry-util-http==0.36b0
Brotli==1.0.9
+loguru==0.6.0
diff --git a/backend/requirements/base.txt b/backend/requirements/base.txt
index dcadfe7409..c2a282a518 100644
--- a/backend/requirements/base.txt
+++ b/backend/requirements/base.txt
@@ -21,6 +21,7 @@ asgiref==3.4.1
# channels-redis
# daphne
# django
+ # opentelemetry-instrumentation-asgi
# uvicorn
async-timeout==4.0.2
# via aioredis
@@ -34,6 +35,8 @@ autobahn==22.7.1
# via daphne
automat==20.2.0
# via twisted
+backoff==2.2.1
+ # via opentelemetry-exporter-otlp-proto-http
billiard==3.6.4.0
# via celery
boto3==1.20.38
@@ -92,7 +95,9 @@ decorator==5.1.1
defusedxml==0.7.1
# via pysaml2
deprecated==1.2.13
- # via redis
+ # via
+ # opentelemetry-api
+ # redis
dj-database-url==0.5.0
# via -r base.in
django==3.2.13
@@ -139,6 +144,8 @@ elementpath==3.0.2
# via xmlschema
faker==8.11.0
# via -r base.in
+googleapis-common-protos==1.58.0
+ # via opentelemetry-exporter-otlp-proto-http
gunicorn==20.1.0
# via -r base.in
h11==0.14.0
@@ -171,6 +178,8 @@ jsonschema==4.16.0
# via drf-spectacular
kombu==5.2.4
# via celery
+loguru==0.6.0
+ # via -r base.in
msgpack==1.0.4
# via channels-redis
ndg-httpsclient==0.5.1
@@ -179,12 +188,110 @@ netifaces==0.11.0
# via advocate
oauthlib==3.2.1
# via requests-oauthlib
+opentelemetry-api==1.15.0
+ # via
+ # -r base.in
+ # opentelemetry-exporter-otlp-proto-http
+ # opentelemetry-instrumentation
+ # opentelemetry-instrumentation-aiohttp-client
+ # opentelemetry-instrumentation-asgi
+ # opentelemetry-instrumentation-botocore
+ # opentelemetry-instrumentation-celery
+ # opentelemetry-instrumentation-dbapi
+ # opentelemetry-instrumentation-django
+ # opentelemetry-instrumentation-grpc
+ # opentelemetry-instrumentation-logging
+ # opentelemetry-instrumentation-psycopg2
+ # opentelemetry-instrumentation-redis
+ # opentelemetry-instrumentation-requests
+ # opentelemetry-instrumentation-wsgi
+ # opentelemetry-sdk
+opentelemetry-exporter-otlp-proto-http==1.15.0
+ # via -r base.in
+opentelemetry-instrumentation==0.36b0
+ # via
+ # -r base.in
+ # opentelemetry-instrumentation-aiohttp-client
+ # opentelemetry-instrumentation-asgi
+ # opentelemetry-instrumentation-botocore
+ # opentelemetry-instrumentation-celery
+ # opentelemetry-instrumentation-dbapi
+ # opentelemetry-instrumentation-django
+ # opentelemetry-instrumentation-grpc
+ # opentelemetry-instrumentation-logging
+ # opentelemetry-instrumentation-psycopg2
+ # opentelemetry-instrumentation-redis
+ # opentelemetry-instrumentation-requests
+ # opentelemetry-instrumentation-wsgi
+opentelemetry-instrumentation-aiohttp-client==0.36b0
+ # via -r base.in
+opentelemetry-instrumentation-asgi==0.36b0
+ # via -r base.in
+opentelemetry-instrumentation-botocore==0.36b0
+ # via -r base.in
+opentelemetry-instrumentation-celery==0.36b0
+ # via -r base.in
+opentelemetry-instrumentation-dbapi==0.36b0
+ # via
+ # -r base.in
+ # opentelemetry-instrumentation-psycopg2
+opentelemetry-instrumentation-django==0.36b0
+ # via -r base.in
+opentelemetry-instrumentation-grpc==0.36b0
+ # via -r base.in
+opentelemetry-instrumentation-logging==0.36b0
+ # via -r base.in
+opentelemetry-instrumentation-psycopg2==0.36b0
+ # via -r base.in
+opentelemetry-instrumentation-redis==0.36b0
+ # via -r base.in
+opentelemetry-instrumentation-requests==0.36b0
+ # via -r base.in
+opentelemetry-instrumentation-wsgi==0.36b0
+ # via
+ # -r base.in
+ # opentelemetry-instrumentation-django
+opentelemetry-proto==1.15.0
+ # via
+ # -r base.in
+ # opentelemetry-exporter-otlp-proto-http
+opentelemetry-sdk==1.15.0
+ # via
+ # -r base.in
+ # opentelemetry-exporter-otlp-proto-http
+ # opentelemetry-instrumentation-grpc
+opentelemetry-semantic-conventions==0.36b0
+ # via
+ # -r base.in
+ # opentelemetry-instrumentation-aiohttp-client
+ # opentelemetry-instrumentation-asgi
+ # opentelemetry-instrumentation-botocore
+ # opentelemetry-instrumentation-celery
+ # opentelemetry-instrumentation-dbapi
+ # opentelemetry-instrumentation-django
+ # opentelemetry-instrumentation-grpc
+ # opentelemetry-instrumentation-redis
+ # opentelemetry-instrumentation-requests
+ # opentelemetry-instrumentation-wsgi
+ # opentelemetry-sdk
+opentelemetry-util-http==0.36b0
+ # via
+ # -r base.in
+ # opentelemetry-instrumentation-aiohttp-client
+ # opentelemetry-instrumentation-asgi
+ # opentelemetry-instrumentation-django
+ # opentelemetry-instrumentation-requests
+ # opentelemetry-instrumentation-wsgi
packaging==21.3
# via redis
pillow==9.0.0
# via -r base.in
prompt-toolkit==3.0.31
# via click-repl
+protobuf==4.21.12
+ # via
+ # googleapis-common-protos
+ # opentelemetry-proto
psutil==5.9.0
# via -r base.in
psycopg2==2.9.1
@@ -247,6 +354,7 @@ requests==2.26.0
# via
# -r base.in
# advocate
+ # opentelemetry-exporter-otlp-proto-http
# pysaml2
# requests-oauthlib
requests-oauthlib==1.3.1
@@ -282,7 +390,9 @@ twisted[tls]==22.1.0
txaio==22.2.1
# via autobahn
typing-extensions==4.4.0
- # via twisted
+ # via
+ # opentelemetry-sdk
+ # twisted
unicodecsv==0.14.1
# via -r base.in
uritemplate==4.1.1
@@ -312,7 +422,13 @@ websockets==10.3
# -r base.in
# uvicorn
wrapt==1.14.1
- # via deprecated
+ # via
+ # deprecated
+ # opentelemetry-instrumentation
+ # opentelemetry-instrumentation-aiohttp-client
+ # opentelemetry-instrumentation-dbapi
+ # opentelemetry-instrumentation-grpc
+ # opentelemetry-instrumentation-redis
xmlschema==2.1.0
# via pysaml2
zipp==3.5.0
diff --git a/backend/src/baserow/api/user/serializers.py b/backend/src/baserow/api/user/serializers.py
index ed777e249b..b1995ecaed 100644
--- a/backend/src/baserow/api/user/serializers.py
+++ b/backend/src/baserow/api/user/serializers.py
@@ -5,6 +5,7 @@ from django.contrib.auth import get_user_model
from django.contrib.auth.models import AbstractUser
from drf_spectacular.utils import extend_schema_serializer
+from opentelemetry import metrics
from rest_framework import serializers
from rest_framework.request import Request
from rest_framework_simplejwt.serializers import (
@@ -32,6 +33,13 @@ from baserow.core.user.utils import (
User = get_user_model()
+meter = metrics.get_meter(__name__)
+token_refreshes_counter = meter.create_counter(
+ "baserow.token_refreshes",
+ unit="1",
+ description="The number of token refreshes.",
+)
+
class SubjectUserSerializer(serializers.ModelSerializer):
class Meta:
@@ -250,6 +258,7 @@ class TokenRefreshWithUserSerializer(TokenRefreshSerializer):
user = get_user_from_token(attrs["refresh"], RefreshToken)
data = generate_session_tokens_for_user(user)
data.update(**get_all_user_data_serialized(user, self.context["request"]))
+ token_refreshes_counter.add(1, {"baserow.user_id": user.id})
return data
diff --git a/backend/src/baserow/config/asgi.py b/backend/src/baserow/config/asgi.py
index 5eae8a14f3..db205a699d 100644
--- a/backend/src/baserow/config/asgi.py
+++ b/backend/src/baserow/config/asgi.py
@@ -1,14 +1,19 @@
-import django
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter
+from baserow.core.telemetry.telemetry import setup_logging, setup_telemetry
from baserow.ws.routers import websocket_router
-django.setup()
+# The telemetry instrumentation library setup needs to run prior to django's setup.
+setup_telemetry(add_django_instrumentation=True)
django_asgi_app = get_asgi_application()
+# It is critical to setup our own logging after django has been setup and done its own
+# logging setup. Otherwise Django will try to destroy and log handlers we added prior.
+setup_logging()
+
application = ProtocolTypeRouter(
{"http": django_asgi_app, "websocket": websocket_router}
)
diff --git a/backend/src/baserow/config/settings/base.py b/backend/src/baserow/config/settings/base.py
index 7de8a95c49..8ce809ea12 100644
--- a/backend/src/baserow/config/settings/base.py
+++ b/backend/src/baserow/config/settings/base.py
@@ -1,6 +1,5 @@
import datetime
import importlib
-import logging
import os
import re
from decimal import Decimal
@@ -730,6 +729,7 @@ LOGGING = {
},
}
+
# Now incorrectly named old variable, previously we would run `sync_templates` prior
# to starting the gunicorn server in Docker. This variable would prevent that from
# happening. Now we sync_templates in an async job triggered after migration.
@@ -784,6 +784,6 @@ for plugin in [*BASEROW_BUILT_IN_PLUGINS, *BASEROW_BACKEND_PLUGIN_NAMES]:
# This settings object is an AttrDict shadowing our local variables so the
# plugin can access the Django settings and modify them prior to startup.
result = mod.setup(AttrDict(vars()))
- except ImportError:
- logger = logging.getLogger(__name__)
- logger.warning("Could not import %s", plugin)
+ except ImportError as e:
+ print("Could not import %s", plugin)
+ print(e)
diff --git a/backend/src/baserow/config/wsgi.py b/backend/src/baserow/config/wsgi.py
index 1210aed92f..f80362267e 100644
--- a/backend/src/baserow/config/wsgi.py
+++ b/backend/src/baserow/config/wsgi.py
@@ -9,4 +9,13 @@ https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
from django.core.wsgi import get_wsgi_application
+from baserow.core.telemetry.telemetry import setup_logging, setup_telemetry
+
+# The telemetry instrumentation library setup needs to run prior to django's setup.
+setup_telemetry(add_django_instrumentation=True)
+
application = get_wsgi_application()
+
+# It is critical to setup our own logging after django has been setup and done its own
+# logging setup. Otherwise Django will try to destroy and log handlers we added prior.
+setup_logging()
diff --git a/backend/src/baserow/contrib/database/airtable/airtable_column_types.py b/backend/src/baserow/contrib/database/airtable/airtable_column_types.py
index 3c04f863fe..4d7318a327 100644
--- a/backend/src/baserow/contrib/database/airtable/airtable_column_types.py
+++ b/backend/src/baserow/contrib/database/airtable/airtable_column_types.py
@@ -1,10 +1,10 @@
-import logging
import traceback
from datetime import datetime
from decimal import Decimal
from django.core.exceptions import ValidationError
+from loguru import logger
from pytz import UTC
from pytz import timezone as pytz_timezone
@@ -32,8 +32,6 @@ from baserow.contrib.database.fields.registries import field_type_registry
from .helpers import import_airtable_date_type_options, set_select_options_on_field
from .registry import AirtableColumnType
-logger = logging.getLogger(__name__)
-
class TextAirtableColumnType(AirtableColumnType):
type = "text"
diff --git a/backend/src/baserow/contrib/database/api/rows/serializers.py b/backend/src/baserow/contrib/database/api/rows/serializers.py
index cef7afd025..db083fdcf4 100644
--- a/backend/src/baserow/contrib/database/api/rows/serializers.py
+++ b/backend/src/baserow/contrib/database/api/rows/serializers.py
@@ -1,10 +1,10 @@
-import logging
from copy import deepcopy
from typing import Dict, List
from django.conf import settings
from django.db.models.base import ModelBase
+from loguru import logger
from rest_framework import serializers
from baserow.api.serializers import get_example_pagination_serializer_class
@@ -12,8 +12,6 @@ from baserow.api.utils import get_serializer_class
from baserow.contrib.database.fields.registries import field_type_registry
from baserow.contrib.database.rows.registries import row_metadata_registry
-logger = logging.getLogger(__name__)
-
class RowSerializer(serializers.ModelSerializer):
class Meta:
diff --git a/backend/src/baserow/contrib/database/export/handler.py b/backend/src/baserow/contrib/database/export/handler.py
index ef93c2c037..3ff6ee46a4 100755
--- a/backend/src/baserow/contrib/database/export/handler.py
+++ b/backend/src/baserow/contrib/database/export/handler.py
@@ -1,4 +1,3 @@
-import logging
import uuid
from io import BytesIO
from os.path import join
@@ -10,6 +9,8 @@ from django.core.files.storage import default_storage
from django.db import transaction
from django.utils import timezone
+from loguru import logger
+
from baserow.contrib.database.export.models import (
EXPORT_JOB_CANCELLED_STATUS,
EXPORT_JOB_EXPIRED_STATUS,
@@ -35,8 +36,6 @@ from .exceptions import (
from .file_writer import PaginatedExportJobFileWriter
from .registries import TableExporter, table_exporter_registry
-logger = logging.getLogger(__name__)
-
User = get_user_model()
diff --git a/backend/src/baserow/contrib/database/fields/field_types.py b/backend/src/baserow/contrib/database/fields/field_types.py
index 068477eed7..62591e4076 100644
--- a/backend/src/baserow/contrib/database/fields/field_types.py
+++ b/backend/src/baserow/contrib/database/fields/field_types.py
@@ -1,4 +1,3 @@
-import logging
import re
from abc import ABC, abstractmethod
from collections import defaultdict
@@ -22,6 +21,7 @@ from django.utils.timezone import make_aware
from dateutil import parser
from dateutil.parser import ParserError
+from loguru import logger
from pytz import all_timezones, timezone
from rest_framework import serializers
@@ -140,8 +140,6 @@ if TYPE_CHECKING:
)
from baserow.contrib.database.table.models import GeneratedTableModel
-logger = logging.getLogger(__name__)
-
class TextFieldMatchingRegexFieldType(FieldType, ABC):
"""
diff --git a/backend/src/baserow/contrib/database/fields/handler.py b/backend/src/baserow/contrib/database/fields/handler.py
index 626059d8bd..16e980f754 100644
--- a/backend/src/baserow/contrib/database/fields/handler.py
+++ b/backend/src/baserow/contrib/database/fields/handler.py
@@ -1,4 +1,3 @@
-import logging
import traceback
from copy import deepcopy
from typing import (
@@ -20,6 +19,8 @@ from django.db import connection
from django.db.models import QuerySet
from django.db.utils import DatabaseError, DataError, ProgrammingError
+from loguru import logger
+from opentelemetry import trace
from psycopg2 import sql
from baserow.contrib.database.db.schema import (
@@ -48,6 +49,7 @@ from baserow.contrib.database.table.models import Table
from baserow.contrib.database.views.handler import ViewHandler
from baserow.core.handler import CoreHandler
from baserow.core.models import TrashEntry
+from baserow.core.telemetry.utils import baserow_trace_methods
from baserow.core.trash.exceptions import RelatedTableTrashedException
from baserow.core.trash.handler import TrashHandler
from baserow.core.utils import (
@@ -85,7 +87,7 @@ from .signals import (
field_updated,
)
-logger = logging.getLogger(__name__)
+tracer = trace.get_tracer(__name__)
def _validate_field_name(
@@ -141,7 +143,7 @@ def _validate_field_name(
T = TypeVar("T", bound="Field")
-class FieldHandler:
+class FieldHandler(metaclass=baserow_trace_methods(tracer)):
def get_field(
self,
field_id: int,
diff --git a/backend/src/baserow/contrib/database/fields/registries.py b/backend/src/baserow/contrib/database/fields/registries.py
index dbf882cf0b..817e3e586e 100644
--- a/backend/src/baserow/contrib/database/fields/registries.py
+++ b/backend/src/baserow/contrib/database/fields/registries.py
@@ -50,6 +50,7 @@ class FieldType(
ImportExportMixin,
Instance,
):
+
"""
This abstract class represents a custom field type that can be added to the
field type registry. It must be extended so customisation can be done. Each field
diff --git a/backend/src/baserow/contrib/database/formula/exceptions.py b/backend/src/baserow/contrib/database/formula/exceptions.py
index cb14c241e6..5dc592a9c9 100644
--- a/backend/src/baserow/contrib/database/formula/exceptions.py
+++ b/backend/src/baserow/contrib/database/formula/exceptions.py
@@ -1,15 +1,12 @@
-import logging
-
from django.conf import settings
+from loguru import logger
+
class BaserowFormulaException(Exception):
pass
-logger = logging.getLogger(__name__)
-
-
def formula_exception_handler(e):
"""
Attempts to send formula errors to sentry in non debug mode and logs errors. In
diff --git a/backend/src/baserow/contrib/database/formula/handler.py b/backend/src/baserow/contrib/database/formula/handler.py
index e9451f2804..3035c48b54 100644
--- a/backend/src/baserow/contrib/database/formula/handler.py
+++ b/backend/src/baserow/contrib/database/formula/handler.py
@@ -3,6 +3,8 @@ from typing import Dict, Optional, Set, Type
from django.db.models import Expression, Model
+from opentelemetry import trace
+
from baserow.contrib.database.fields.dependencies.types import FieldDependencies
from baserow.contrib.database.fields.field_cache import FieldCache
from baserow.contrib.database.formula import BaserowFormulaException
@@ -39,11 +41,15 @@ from baserow.contrib.database.formula.types.visitors import (
FieldDependencyExtractingVisitor,
FunctionsUsedVisitor,
)
+from baserow.core.telemetry.utils import baserow_trace_methods
if typing.TYPE_CHECKING:
from baserow.contrib.database.fields.models import FormulaField
+tracer = trace.get_tracer(__name__)
+
+
def _expression_requires_refresh_after_insert(expression: BaserowExpression):
"""
WARNING: This function is directly used by migration code. Please ensure
@@ -70,7 +76,7 @@ def _expression_requires_refresh_after_insert(expression: BaserowExpression):
return any(f.requires_refresh_after_insert for f in functions_used)
-class FormulaHandler:
+class FormulaHandler(metaclass=baserow_trace_methods(tracer)):
"""
Contains all the methods used to interact with formulas and formula fields in
Baserow.
diff --git a/backend/src/baserow/contrib/database/formula/migrations/handler.py b/backend/src/baserow/contrib/database/formula/migrations/handler.py
index 97ce164292..033fbb146e 100644
--- a/backend/src/baserow/contrib/database/formula/migrations/handler.py
+++ b/backend/src/baserow/contrib/database/formula/migrations/handler.py
@@ -1,4 +1,3 @@
-import logging
import math
import traceback
import typing
@@ -8,6 +7,7 @@ from typing import Set
from django.db import transaction
from django.db.models import Min, Q, QuerySet
+from loguru import logger
from tqdm import tqdm
from baserow.contrib.database.fields.field_cache import FieldCache
@@ -24,7 +24,6 @@ from baserow.core.utils import ChildProgressBuilder, Progress
if typing.TYPE_CHECKING:
from baserow.contrib.database.fields.models import Field
-logger = logging.getLogger(__name__)
DEFAULT_FORMULA_MIGRATION_BATCH_SIZE = 100
diff --git a/backend/src/baserow/contrib/database/rows/handler.py b/backend/src/baserow/contrib/database/rows/handler.py
index f30e2e0c23..43172a3412 100644
--- a/backend/src/baserow/contrib/database/rows/handler.py
+++ b/backend/src/baserow/contrib/database/rows/handler.py
@@ -12,6 +12,8 @@ from django.db.models import F, Max, Q, QuerySet
from django.db.models.fields.related import ForeignKey, ManyToManyField
from django.utils.encoding import force_str
+from opentelemetry import metrics, trace
+
from baserow.contrib.database.fields.dependencies.handler import FieldDependencyHandler
from baserow.contrib.database.fields.dependencies.update_collector import (
FieldUpdateCollector,
@@ -31,6 +33,7 @@ from baserow.contrib.database.table.operations import (
)
from baserow.contrib.database.trash.models import TrashedRows
from baserow.core.handler import CoreHandler
+from baserow.core.telemetry.utils import baserow_trace_methods
from baserow.core.trash.handler import TrashHandler
from baserow.core.utils import Progress, get_non_unique_values, grouper
@@ -51,6 +54,8 @@ from .signals import (
rows_updated,
)
+tracer = trace.get_tracer(__name__)
+
GeneratedTableModelForUpdate = NewType(
"GeneratedTableModelForUpdate", GeneratedTableModel
)
@@ -60,6 +65,23 @@ RowsForUpdate = NewType("RowsForUpdate", QuerySet)
BATCH_SIZE = 1024
+meter = metrics.get_meter(__name__)
+rows_created_counter = meter.create_counter(
+ "baserow.rows_created",
+ unit="1",
+ description="The number of rows created in user tables.",
+)
+rows_updated_counter = meter.create_counter(
+ "baserow.rows_updated",
+ unit="1",
+ description="The number of rows updated in user tables.",
+)
+rows_deleted_counter = meter.create_counter(
+ "baserow.rows_deleted",
+ unit="1",
+ description="The number of rows deleted in user tables.",
+)
+
def serialize_errors_recursive(error):
if isinstance(error, dict):
@@ -90,7 +112,7 @@ def prepare_field_errors(field_errors):
}
-class RowHandler:
+class RowHandler(metaclass=baserow_trace_methods(tracer)):
def prepare_values(self, fields, values):
"""
Prepares a set of values so that they can be created or updated in the database.
@@ -655,6 +677,13 @@ class RowHandler:
values, manytomany_values = self.extract_manytomany_values(values, model)
values["order"] = self.get_order_before_row(before, model)[0]
instance = model.objects.create(**values)
+ rows_created_counter.add(
+ 1,
+ {
+ "baserow.table_id": table.id,
+ "baserow.database_id": table.database_id,
+ },
+ )
for name, value in manytomany_values.items():
getattr(instance, name).set(value)
@@ -833,6 +862,13 @@ class RowHandler:
getattr(row, name).set(value)
row.save()
+ rows_updated_counter.add(
+ 1,
+ {
+ "baserow.table_id": table.id,
+ "baserow.database_id": table.database_id,
+ },
+ )
update_collector = FieldUpdateCollector(
table,
@@ -942,6 +978,13 @@ class RowHandler:
inserted_rows = model.objects.bulk_create(
[row for (row, relations) in rows_relationships]
)
+ rows_created_counter.add(
+ len(rows_relationships),
+ {
+ "baserow.table_id": table.id,
+ "baserow.database_id": table.database_id,
+ },
+ )
many_to_many = defaultdict(list)
for index, row in enumerate(inserted_rows):
@@ -1472,6 +1515,13 @@ class RowHandler:
if len(bulk_update_fields) > 0:
model.objects.bulk_update(rows_to_update, bulk_update_fields)
+ rows_updated_counter.add(
+ len(rows_to_update),
+ {
+ "baserow.table_id": table.id,
+ "baserow.database_id": table.database_id,
+ },
+ )
update_collector = FieldUpdateCollector(
table,
@@ -1699,6 +1749,13 @@ class RowHandler:
)
TrashHandler.trash(user, group, table.database, row, parent_id=table.id)
+ rows_deleted_counter.add(
+ 1,
+ {
+ "baserow.table_id": table.id,
+ "baserow.database_id": table.database_id,
+ },
+ )
update_collector = FieldUpdateCollector(table, starting_row_ids=[row.id])
field_cache = FieldCache()
@@ -1795,6 +1852,13 @@ class RowHandler:
TrashHandler.trash(
user, group, table.database, trashed_rows, parent_id=table.id
)
+ rows_deleted_counter.add(
+ len(row_ids),
+ {
+ "baserow.table_id": table.id,
+ "baserow.database_id": table.database_id,
+ },
+ )
updated_field_ids = []
updated_fields = []
diff --git a/backend/src/baserow/contrib/database/table/handler.py b/backend/src/baserow/contrib/database/table/handler.py
index caf533b02e..8704b8e9db 100644
--- a/backend/src/baserow/contrib/database/table/handler.py
+++ b/backend/src/baserow/contrib/database/table/handler.py
@@ -1,4 +1,3 @@
-import logging
import traceback
from typing import Any, Dict, List, NewType, Optional, Tuple, cast
@@ -9,6 +8,9 @@ from django.db.models import QuerySet, Sum
from django.utils import timezone, translation
from django.utils.translation import gettext as _
+from loguru import logger
+from opentelemetry import trace
+
from baserow.contrib.database.db.schema import safe_django_schema_editor
from baserow.contrib.database.fields.constants import RESERVED_BASEROW_FIELD_NAMES
from baserow.contrib.database.fields.exceptions import (
@@ -30,6 +32,7 @@ from baserow.contrib.database.views.handler import ViewHandler
from baserow.contrib.database.views.view_types import GridViewType
from baserow.core.handler import CoreHandler
from baserow.core.registries import application_type_registry
+from baserow.core.telemetry.utils import baserow_trace_methods
from baserow.core.trash.handler import TrashHandler
from baserow.core.utils import ChildProgressBuilder, Progress, find_unused_name
@@ -54,10 +57,10 @@ BATCH_SIZE = 1024
TableForUpdate = NewType("TableForUpdate", Table)
-logger = logging.getLogger(__name__)
+tracer = trace.get_tracer(__name__)
-class TableHandler:
+class TableHandler(metaclass=baserow_trace_methods(tracer)):
def get_table(
self, table_id: int, base_queryset: Optional[QuerySet] = None
) -> Table:
diff --git a/backend/src/baserow/contrib/database/table/models.py b/backend/src/baserow/contrib/database/table/models.py
index 5559e62500..97b96a18dc 100644
--- a/backend/src/baserow/contrib/database/table/models.py
+++ b/backend/src/baserow/contrib/database/table/models.py
@@ -6,6 +6,8 @@ from django.conf import settings
from django.db import models
from django.db.models import F, JSONField, Q, QuerySet
+from opentelemetry import trace
+
from baserow.contrib.database.fields.exceptions import (
FilterFieldNotFound,
OrderByFieldNotFound,
@@ -38,12 +40,15 @@ from baserow.core.mixins import (
OrderableMixin,
TrashableModelMixin,
)
+from baserow.core.telemetry.utils import baserow_trace
from baserow.core.utils import split_comma_separated_string
deconstruct_filter_key_regex = re.compile(
r"filter__field_([0-9]+|created_on|updated_on)__([a-zA-Z0-9_]*)$"
)
+tracer = trace.get_tracer(__name__)
+
class TableModelQuerySet(models.QuerySet):
def enhance_by_fields(self):
@@ -433,6 +438,7 @@ class Table(
def get_database_table_name(self):
return f"{self.USER_TABLE_DATABASE_NAME_PREFIX}{self.id}"
+ @baserow_trace(tracer)
def get_model(
self,
fields=None,
@@ -586,6 +592,12 @@ class Table(
attrs,
)
+ self._after_model_generation(attrs, manytomany_models, model)
+
+ return model
+
+ @baserow_trace(tracer)
+ def _after_model_generation(self, attrs, manytomany_models, model):
# In some situations the field can only be added once the model class has been
# generated. So for each field we will call the after_model_generation with
# the generated model as argument in order to do this. This is for example used
@@ -600,8 +612,7 @@ class Table(
field_object["field"], model, field_object["name"], manytomany_models
)
- return model
-
+ @baserow_trace(tracer)
def _fetch_and_generate_field_attrs(
self,
add_dependencies,
diff --git a/backend/src/baserow/contrib/database/views/handler.py b/backend/src/baserow/contrib/database/views/handler.py
index 3374a97c3a..f880bf9615 100644
--- a/backend/src/baserow/contrib/database/views/handler.py
+++ b/backend/src/baserow/contrib/database/views/handler.py
@@ -14,6 +14,7 @@ from django.db.models import Count, F
from django.db.models.query import QuerySet
import jwt
+from opentelemetry import trace
from redis.exceptions import LockNotOwnedError
from baserow.contrib.database.api.utils import get_include_exclude_field_ids
@@ -59,6 +60,7 @@ from baserow.contrib.database.views.operations import (
from baserow.contrib.database.views.registries import view_ownership_type_registry
from baserow.core.db import specific_iterator
from baserow.core.handler import CoreHandler
+from baserow.core.telemetry.utils import baserow_trace_methods
from baserow.core.trash.handler import TrashHandler
from baserow.core.utils import (
MirrorDict,
@@ -124,8 +126,11 @@ FieldOptionsDict = Dict[int, Dict[str, Any]]
ending_number_regex = re.compile(r"(.+) (\d+)$")
+tracer = trace.get_tracer(__name__)
+
+
+class ViewHandler(metaclass=baserow_trace_methods(tracer)):
-class ViewHandler:
PUBLIC_VIEW_TOKEN_ALGORITHM = "HS256" # nosec
def list_views(
diff --git a/backend/src/baserow/core/action/handler.py b/backend/src/baserow/core/action/handler.py
index b0e94860ae..a0a2489be4 100755
--- a/backend/src/baserow/core/action/handler.py
+++ b/backend/src/baserow/core/action/handler.py
@@ -1,4 +1,3 @@
-import logging
import traceback
from datetime import datetime
from typing import List, Optional, Set, Tuple
@@ -9,7 +8,11 @@ from django.db import transaction
from django.db.models import Q
from django.utils import timezone
+from loguru import logger
+from opentelemetry import trace
+
from baserow.core.exceptions import LockConflict
+from baserow.core.telemetry.utils import baserow_trace, baserow_trace_methods
from .models import Action
from .registries import (
@@ -19,7 +22,7 @@ from .registries import (
)
from .signals import ActionCommandType
-logger = logging.getLogger(__name__)
+tracer = trace.get_tracer(__name__)
def scopes_to_q_filter(scopes: List[ActionScopeStr]):
@@ -40,7 +43,8 @@ class OneActionHasErrorAndCannotBeRedone(Exception):
"""
-class ActionHandler:
+class ActionHandler(metaclass=baserow_trace_methods(tracer)):
+
"""
Contains methods to do high level operations on ActionType's like undoing or
redoing them.
@@ -86,6 +90,7 @@ class ActionHandler:
raise exc
@classmethod
+ @baserow_trace(tracer)
def undo(
cls, user: AbstractUser, scopes: List[ActionScopeStr], session: str
) -> List[Action]:
@@ -162,6 +167,7 @@ class ActionHandler:
raise exc
@classmethod
+ @baserow_trace(tracer)
def redo(
cls, user: AbstractUser, scopes: List[ActionScopeStr], session: str
) -> List[Action]:
diff --git a/backend/src/baserow/core/action/registries.py b/backend/src/baserow/core/action/registries.py
index f590e1e7fb..3bbd122e48 100755
--- a/backend/src/baserow/core/action/registries.py
+++ b/backend/src/baserow/core/action/registries.py
@@ -8,6 +8,7 @@ from django.contrib.auth.models import AbstractUser
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
+from opentelemetry import trace
from rest_framework import serializers
from baserow.api.sessions import (
@@ -16,10 +17,13 @@ from baserow.api.sessions import (
)
from baserow.core.models import Group
from baserow.core.registry import Instance, Registry
+from baserow.core.telemetry.utils import add_baserow_trace_attrs, baserow_trace_methods
from .models import Action
from .signals import ActionCommandType, action_done
+tracer = trace.get_tracer(__name__)
+
# An alias type of a str (its exactly a str, just with a different name in the type
# system). We use this instead of a normal str for type safety ensuring
# only str's returned by ActionScopeType.value and
@@ -129,7 +133,10 @@ def render_action_type_description(
return f"{description.long % params_dict}"
-class ActionType(Instance, abc.ABC):
+class ActionType(
+ Instance,
+ metaclass=baserow_trace_methods(tracer, only=["do", "undo", "redo"], abc=True),
+):
type: str = NotImplemented
description: ActionTypeDescription = ActionTypeDescription()
@@ -224,6 +231,13 @@ class ActionType(Instance, abc.ABC):
action_group = get_client_undo_redo_action_group_id(user)
action_timestamp = timestamp if timestamp else timezone.now()
+ add_baserow_trace_attrs(
+ action_user_id=user.id,
+ group_id=getattr(group, "id", None),
+ action_scope=scope,
+ action_type=cls.type,
+ )
+
action_done.send(
sender=cls,
user=user,
@@ -260,7 +274,7 @@ class ActionType(Instance, abc.ABC):
cls.send_action_done_signal(user, dataclasses.asdict(params), scope, group)
-class UndoableActionTypeMixin(abc.ABC):
+class UndoableActionTypeMixin:
@classmethod
@abc.abstractmethod
def undo(cls, user: AbstractUser, params: Any, action_being_undone: Action):
@@ -348,7 +362,10 @@ class UndoableActionCustomCleanupMixin(abc.ABC):
pass
-class UndoableActionType(UndoableActionTypeMixin, ActionType):
+class UndoableActionType(
+ UndoableActionTypeMixin,
+ ActionType,
+):
pass
diff --git a/backend/src/baserow/core/action/signals.py b/backend/src/baserow/core/action/signals.py
index 4c0c45fa50..e8b2a3474a 100755
--- a/backend/src/baserow/core/action/signals.py
+++ b/backend/src/baserow/core/action/signals.py
@@ -1,6 +1,8 @@
from enum import Enum
-from django.dispatch import Signal
+from django.dispatch import Signal, receiver
+
+from loguru import logger
class ActionCommandType(Enum):
@@ -10,3 +12,23 @@ class ActionCommandType(Enum):
action_done = Signal()
+
+
+@receiver(action_done)
+def log_action_receiver(
+ sender,
+ user,
+ action_type,
+ action_params,
+ action_timestamp,
+ action_command_type,
+ group,
+ **kwargs,
+):
+ logger.info(
+ "{action_command_type}: group={group_id} action_type={action_type} user={user_id}",
+ action_command_type=action_command_type.name.lower(),
+ group_id=group.id if group else "",
+ action_type=action_type.type,
+ user_id=user.id,
+ )
diff --git a/backend/src/baserow/core/handler.py b/backend/src/baserow/core/handler.py
index 606ae5e249..61d240ee28 100755
--- a/backend/src/baserow/core/handler.py
+++ b/backend/src/baserow/core/handler.py
@@ -16,6 +16,7 @@ from django.db.models import Count, Prefetch, Q, QuerySet
from django.utils import translation
from itsdangerous import URLSafeSerializer
+from opentelemetry import trace
from tqdm import tqdm
from baserow.core.user.utils import normalize_email_address
@@ -92,6 +93,7 @@ from .signals import (
group_user_updated,
groups_reordered,
)
+from .telemetry.utils import baserow_trace_methods, disable_instrumentation
from .trash.handler import TrashHandler
from .types import Actor, ContextObject, PermissionCheck, PermissionObjectResult
from .utils import (
@@ -105,8 +107,10 @@ User = get_user_model()
GroupForUpdate = NewType("GroupForUpdate", Group)
+tracer = trace.get_tracer(__name__)
-class CoreHandler:
+
+class CoreHandler(metaclass=baserow_trace_methods(tracer)):
def get_settings(self):
"""
Returns a settings model instance containing all the admin configured settings.
@@ -1524,6 +1528,10 @@ class CoreHandler:
return template
@transaction.atomic
+ # This single function generates a huge number of spans and events, we know it
+ # is slow, and so we disable instrumenting it to save significant resources in
+ # telemetry platforms receiving the instrumentation.
+ @disable_instrumentation
def sync_templates(self, storage=None, template_search_glob="*.json"):
"""
Synchronizes the JSON template files with the templates stored in the database.
diff --git a/backend/src/baserow/core/jobs/handler.py b/backend/src/baserow/core/jobs/handler.py
index a85e814455..87e92cd135 100644
--- a/backend/src/baserow/core/jobs/handler.py
+++ b/backend/src/baserow/core/jobs/handler.py
@@ -1,4 +1,3 @@
-import logging
from typing import List, Optional, Type
from django.conf import settings
@@ -18,8 +17,6 @@ from .registries import job_type_registry
from .tasks import run_async_job
from .types import AnyJob
-logger = logging.getLogger(__name__)
-
class JobHandler:
def run(self, job: AnyJob):
diff --git a/backend/src/baserow/core/jobs/registries.py b/backend/src/baserow/core/jobs/registries.py
index 32c72709e6..29de38c3f8 100644
--- a/backend/src/baserow/core/jobs/registries.py
+++ b/backend/src/baserow/core/jobs/registries.py
@@ -2,6 +2,8 @@ from typing import Any, Dict
from django.contrib.auth.models import AbstractUser
+from opentelemetry import trace
+
from baserow.core.db import transaction_atomic
from baserow.core.registry import (
CustomFieldsInstanceMixin,
@@ -12,19 +14,24 @@ from baserow.core.registry import (
ModelRegistryMixin,
Registry,
)
+from baserow.core.telemetry.utils import baserow_trace_methods
from baserow.core.utils import Progress
from .exceptions import JobTypeAlreadyRegistered, JobTypeDoesNotExist
from .models import Job
from .types import AnyJob
+tracer = trace.get_tracer(__name__)
+
class JobType(
CustomFieldsInstanceMixin,
ModelInstanceMixin,
MapAPIExceptionsInstanceMixin,
Instance,
+ metaclass=baserow_trace_methods(tracer, only="do"),
):
+
"""
This abstract class represents a custom job type that can be added to the
job type registry. It must be extended so customization can be done. Each job
diff --git a/backend/src/baserow/core/tasks.py b/backend/src/baserow/core/tasks.py
index 3616aa26c7..ad68d30441 100644
--- a/backend/src/baserow/core/tasks.py
+++ b/backend/src/baserow/core/tasks.py
@@ -4,6 +4,7 @@ from baserow.config.celery import app
from .action.tasks import cleanup_old_actions, setup_periodic_action_tasks
from .snapshots.tasks import delete_expired_snapshots
+from .telemetry.tasks import initialize_otel
from .trash.tasks import (
mark_old_trash_for_permanent_deletion,
permanently_delete_marked_trash,
@@ -34,4 +35,5 @@ __all__ = [
"run_calculate_storage",
"check_pending_account_deletion",
"delete_expired_snapshots",
+ "initialize_otel",
]
diff --git a/backend/src/baserow/core/telemetry/__init__.py b/backend/src/baserow/core/telemetry/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/backend/src/baserow/core/telemetry/tasks.py b/backend/src/baserow/core/telemetry/tasks.py
new file mode 100644
index 0000000000..7cdc4460ee
--- /dev/null
+++ b/backend/src/baserow/core/telemetry/tasks.py
@@ -0,0 +1,8 @@
+from celery.signals import worker_process_init
+
+from baserow.core.telemetry.telemetry import setup_telemetry
+
+
+@worker_process_init.connect
+def initialize_otel(**kwargs):
+ setup_telemetry(add_django_instrumentation=False)
diff --git a/backend/src/baserow/core/telemetry/telemetry.py b/backend/src/baserow/core/telemetry/telemetry.py
new file mode 100644
index 0000000000..8b33e7d539
--- /dev/null
+++ b/backend/src/baserow/core/telemetry/telemetry.py
@@ -0,0 +1,162 @@
+import logging
+import os
+import sys
+
+from opentelemetry import metrics, trace
+from opentelemetry._logs import set_logger_provider
+from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
+from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
+from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
+from opentelemetry.instrumentation.botocore import BotocoreInstrumentor
+from opentelemetry.instrumentation.celery import CeleryInstrumentor
+from opentelemetry.instrumentation.django import DjangoInstrumentor
+from opentelemetry.instrumentation.psycopg2 import Psycopg2Instrumentor
+from opentelemetry.instrumentation.redis import RedisInstrumentor
+from opentelemetry.instrumentation.requests import RequestsInstrumentor
+from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
+from opentelemetry.sdk._logs._internal.export import BatchLogRecordProcessor
+from opentelemetry.sdk.metrics import MeterProvider
+from opentelemetry.sdk.metrics._internal.export import PeriodicExportingMetricReader
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import BatchSpanProcessor
+from opentelemetry.trace import ProxyTracerProvider
+
+
+class LogGuruCompatibleLoggerHandler(LoggingHandler):
+ def emit(self, record: logging.LogRecord) -> None:
+ # The Otel exporter does not handle nested dictionaries. Loguru stores all of
+ # the extra log context developers can add on the extra dict. Here unnest
+ # them as attributes on the record itself so otel can export them properly.
+ for k, v in record.extra.items():
+ setattr(record, f"baserow.{k}", v)
+ del record.extra
+
+ # by default otel doesn't send funcName, rename it so it does.
+ setattr(record, "python_function", record.funcName)
+ super().emit(record)
+
+
+def setup_logging():
+ """
+ This function configures loguru and optionally sets up open telemetry log exporting
+ using a loguru sink.
+
+ It is not run as part of setup_logging_and_telemetry as we want this to run
+ after Django has set up its own logging. If we run prior to Django, it will teardown
+ any log handlers we set up in here causing errors due to the exporters being flushed
+ immediately with no contents.
+ """
+
+ from loguru import logger
+
+ # A slightly customized default loguru format which includes the process id.
+ loguru_format = (
+ f"{os.getpid()}|"
+ "{time:YYYY-MM-DD HH:mm:ss.SSS}|"
+ "{level}|"
+ "{name}:"
+ "{function}:"
+ "{line} - "
+ "{message}"
+ )
+
+ # Remove the default loguru stderr sink
+ logger.remove()
+ # Replace it with our format, loguru recommends sending application logs to stderr.
+ logger.add(sys.stderr, format=loguru_format)
+ logger.info("Logger setup.")
+ if otel_is_enabled():
+ _setup_log_exporting(logger)
+
+
+def otel_is_enabled():
+ env_var_set = bool(os.getenv("BASEROW_ENABLE_OTEL", False))
+ not_in_tests = (
+ os.getenv("DJANGO_SETTINGS_MODULE", "").strip()
+ != "baserow.config.settings.test"
+ )
+ return env_var_set and not_in_tests
+
+
+def setup_telemetry(add_django_instrumentation: bool):
+ """
+ Sets up logging and when the env var BASEROW_ENABLE_OTEL is set to any non-blank
+ string and this function is called metrics will be setup and sent according to
+ the OTEL env vars you can find described at:
+ - https://opentelemetry.io/docs/reference/specification/protocol/exporter/
+ - https://opentelemetry.io/docs/reference/specification/sdk-environment-variables/
+
+ :param add_django_instrumentation: Enables specific instrumentation for a django
+ process that is processing requests. Don't enable this for a celery process etc.
+ """
+
+ if otel_is_enabled():
+ existing_provider = trace.get_tracer_provider()
+ if not isinstance(existing_provider, ProxyTracerProvider):
+ print("Provider already configured not reconfiguring...")
+ else:
+ provider = TracerProvider()
+ processor = BatchSpanProcessor(OTLPSpanExporter())
+ provider.add_span_processor(processor)
+ trace.set_tracer_provider(provider)
+
+ reader = PeriodicExportingMetricReader(OTLPMetricExporter())
+ provider = MeterProvider(
+ metric_readers=[reader],
+ )
+ metrics.set_meter_provider(provider)
+
+ _setup_standard_backend_instrumentation()
+
+ print("Configured default backend instrumentation")
+ if add_django_instrumentation:
+ print("Adding Django request instrumentation also.")
+ _setup_django_process_instrumentation()
+
+ print("Telemetry enabled!")
+ else:
+ print("Not configuring telemetry due to BASEROW_ENABLE_OTEL not being set.")
+
+
+def _setup_log_exporting(logger):
+ from django.conf import settings
+
+ logger_provider = LoggerProvider()
+ set_logger_provider(logger_provider)
+ exporter = OTLPLogExporter()
+ handler = LogGuruCompatibleLoggerHandler(
+ level=settings.BASEROW_BACKEND_LOG_LEVEL,
+ logger_provider=logger_provider,
+ )
+ logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter))
+ logger.add(handler, format="{message}")
+ logger.info("Logger open telemetry exporting setup.")
+
+
+def _setup_standard_backend_instrumentation():
+ BotocoreInstrumentor().instrument()
+ Psycopg2Instrumentor().instrument()
+ RedisInstrumentor().instrument()
+ RequestsInstrumentor().instrument()
+ CeleryInstrumentor().instrument()
+
+
+def _setup_django_process_instrumentation():
+ def response_hook(span, request, response):
+
+ if hasattr(request, "user"):
+
+ def _set(name, *attr):
+ value = request.user
+ for a in attr:
+ value = getattr(value, a, None)
+ if value:
+ span.set_attribute(name, value)
+
+ _set("user.id", "id")
+ _set("user.untrusted_client_session_id", "untrusted_client_session_id")
+ _set("user.database_token_id", "user_token", "id")
+
+ DjangoInstrumentor().instrument(
+ response_hook=response_hook,
+ )
diff --git a/backend/src/baserow/core/telemetry/utils.py b/backend/src/baserow/core/telemetry/utils.py
new file mode 100644
index 0000000000..31617e3aa9
--- /dev/null
+++ b/backend/src/baserow/core/telemetry/utils.py
@@ -0,0 +1,134 @@
+import functools
+import inspect
+from abc import ABCMeta
+from typing import List, Optional, Union
+
+from opentelemetry.context import attach, detach, set_value
+from opentelemetry.trace import Status, StatusCode, Tracer, get_current_span
+
+
+def disable_instrumentation(wrapped_function):
+ @functools.wraps(wrapped_function)
+ def _wrapper(*args, **kwargs):
+ token = attach(set_value("suppress_instrumentation", True))
+ result = wrapped_function(*args, **kwargs)
+ detach(token)
+ return result
+
+ return _wrapper
+
+
+# attrs don't include the module name to keep them short and easier to see so we add
+# baserow manually.
+BASEROW_OTEL_TRACE_ATTR_PREFIX = "baserow."
+
+
+def _baserow_trace_func(wrapped_func, tracer: Tracer):
+ @functools.wraps(wrapped_func)
+ def _wrapper(*args, **kwargs):
+ with tracer.start_as_current_span(
+ wrapped_func.__module__ + "." + wrapped_func.__qualname__
+ ) as span:
+ try:
+ result = wrapped_func(*args, **kwargs)
+ except Exception as ex:
+ span.set_status(Status(StatusCode.ERROR))
+ span.record_exception(ex)
+ raise ex
+
+ return result
+
+ return _wrapper
+
+
+def baserow_trace_methods(
+ tracer: Tracer,
+ only: Optional[Union[str, List[str]]] = None,
+ exclude: Optional[Union[str, List[str]]] = None,
+ abc: bool = False,
+):
+ """
+ Automatically traces all public methods, or specific methods of a class depending
+ on the arguments.
+
+ You need to use this if you want to say, trace every implementation of an abstract
+ method as decorating the method itself will get overriden by the subclasses where-as
+ this metaclass will wrap the method when the subclass itself is created (the class
+ not the instances!)
+
+ If you want to use this metaclass and abc.ABC, use this and set abc=True.
+
+ Using a metaclass is the python recommended way of automatically decorating
+ all/some functions in a class.
+
+ :param tracer: An otel Tracer, add `tracer = trace.get_tracer(__name__)` to the top
+ of your file to get one.
+ :param only: The name of the only function you want to trace or a list of names.
+ :param exclude: The name of the function you do not want to trace or a list of
+ names.
+ :param abc: Whether this class should also be an abstract base class.
+ """
+
+ if only and not isinstance(only, list):
+ only = [only]
+ if exclude and not isinstance(exclude, list):
+ exclude = [exclude]
+
+ super_class = ABCMeta if abc else type
+
+ class TraceMethodsMetaClass(super_class):
+ def __new__(cls, name, bases, local):
+ for attr in local:
+ if cls._should_trace_attr(attr):
+ continue
+ value = local[attr]
+ if inspect.isfunction(value):
+ local[attr] = _baserow_trace_func(value, tracer)
+ return super().__new__(cls, name, bases, local)
+
+ @staticmethod
+ def _should_trace_attr(attr):
+ return (
+ attr.startswith("_")
+ or (only and attr not in only)
+ or (exclude and attr in exclude)
+ )
+
+ return TraceMethodsMetaClass
+
+
+def baserow_trace(tracer):
+ """
+ Decorates a function to send a span of its execution. This will let you see how
+ long the function took in your telemetry platform.
+
+ :param tracer: An otel Tracer, add `tracer = trace.get_tracer(__name__)` to the top
+ of your file to get one.
+ """
+
+ if not isinstance(tracer, Tracer):
+ raise Exception(
+ f"Must provider a tracer to baserow_trace, instead you gave me a "
+ f"{type(tracer)}. Get "
+ "one using "
+ "`tracer = trace.get_tracer(__name__)`."
+ )
+
+ def inner(wrapped_function_or_cls):
+ return _baserow_trace_func(wrapped_function_or_cls, tracer)
+
+ return inner
+
+
+def add_baserow_trace_attrs(**kwargs):
+ """
+ Simple helper function for quickly adding attributes to the current span. The
+ attribute names will be prefixed with the baserow. to namespace them properly.
+
+ :param kwargs: Key value pairs, the key will be the attr name prefixed with
+ baserow. and the value will be the span attribute value.
+ """
+
+ span = get_current_span()
+ for key, value in kwargs.items():
+ span.set_attribute(f"{BASEROW_OTEL_TRACE_ATTR_PREFIX}{key}", value)
diff --git a/backend/src/baserow/core/trash/handler.py b/backend/src/baserow/core/trash/handler.py
index e2de67953c..d02186bd15 100755
--- a/backend/src/baserow/core/trash/handler.py
+++ b/backend/src/baserow/core/trash/handler.py
@@ -1,4 +1,3 @@
-import logging
from typing import Any, Dict, List, Optional
from django.conf import settings
@@ -8,6 +7,9 @@ from django.db import IntegrityError, OperationalError, transaction
from django.db.models import QuerySet
from django.utils import timezone
+from loguru import logger
+from opentelemetry import trace
+
from baserow.core.exceptions import (
ApplicationDoesNotExist,
ApplicationNotInGroup,
@@ -16,6 +18,7 @@ from baserow.core.exceptions import (
is_max_lock_exceeded_exception,
)
from baserow.core.models import Application, Group, TrashEntry
+from baserow.core.telemetry.utils import baserow_trace_methods
from baserow.core.trash.exceptions import (
CannotDeleteAlreadyDeletedItem,
CannotRestoreChildBeforeParent,
@@ -32,11 +35,12 @@ from baserow.core.trash.operations import (
from baserow.core.trash.registries import TrashableItemType, trash_item_type_registry
from baserow.core.trash.signals import permanently_deleted
-logger = logging.getLogger(__name__)
User = get_user_model()
+tracer = trace.get_tracer(__name__)
-class TrashHandler:
+
+class TrashHandler(metaclass=baserow_trace_methods(tracer)):
@staticmethod
def trash(
requesting_user: User,
diff --git a/backend/src/baserow/core/user/handler.py b/backend/src/baserow/core/user/handler.py
index 595418624a..4e6c060f9b 100644
--- a/backend/src/baserow/core/user/handler.py
+++ b/backend/src/baserow/core/user/handler.py
@@ -13,6 +13,7 @@ from django.utils import timezone, translation
from django.utils.translation import gettext as _
from itsdangerous import URLSafeTimedSerializer
+from opentelemetry import trace
from baserow.core.auth_provider.handler import PasswordProviderHandler
from baserow.core.auth_provider.models import AuthProviderModel
@@ -32,6 +33,7 @@ from baserow.core.signals import (
)
from baserow.core.trash.handler import TrashHandler
+from ..telemetry.utils import baserow_trace_methods
from .emails import (
AccountDeleted,
AccountDeletionCanceled,
@@ -52,8 +54,10 @@ from .utils import normalize_email_address
User = get_user_model()
+tracer = trace.get_tracer(__name__)
-class UserHandler:
+
+class UserHandler(metaclass=baserow_trace_methods(tracer)):
def get_active_user(
self,
user_id: Optional[int] = None,
diff --git a/backend/src/baserow/gunicorn.config.py b/backend/src/baserow/gunicorn.config.py
new file mode 100644
index 0000000000..bc4132722e
--- /dev/null
+++ b/backend/src/baserow/gunicorn.config.py
@@ -0,0 +1,5 @@
+from baserow.core.telemetry.telemetry import setup_telemetry
+
+
+def post_fork(server, worker):
+ setup_telemetry(add_django_instrumentation=True)
diff --git a/changelog/entries/unreleased/feature/1518_add_open_telemetry_exporters_for_logging_traces_and_metrics_.json b/changelog/entries/unreleased/feature/1518_add_open_telemetry_exporters_for_logging_traces_and_metrics_.json
new file mode 100644
index 0000000000..86ba2c94f9
--- /dev/null
+++ b/changelog/entries/unreleased/feature/1518_add_open_telemetry_exporters_for_logging_traces_and_metrics_.json
@@ -0,0 +1,7 @@
+{
+ "type": "feature",
+ "message": "Add open telemetry exporters for logging, traces and metrics enabled using the BASEROW_ENABLE_OTEL env var.",
+ "issue_number": 1518,
+ "bullet_points": [],
+ "created_at": "2023-02-23"
+}
\ No newline at end of file
diff --git a/deploy/all-in-one/supervisor/default_baserow_env.sh b/deploy/all-in-one/supervisor/default_baserow_env.sh
index c25910a976..ea29756744 100755
--- a/deploy/all-in-one/supervisor/default_baserow_env.sh
+++ b/deploy/all-in-one/supervisor/default_baserow_env.sh
@@ -47,6 +47,9 @@ export SYNC_TEMPLATES_ON_STARTUP=${SYNC_TEMPLATES_ON_STARTUP:-true}
export BASEROW_TRIGGER_SYNC_TEMPLATES_AFTER_MIGRATION=${BASEROW_TRIGGER_SYNC_TEMPLATES_AFTER_MIGRATION:-$SYNC_TEMPLATES_ON_STARTUP}
export MIGRATE_ON_STARTUP=${MIGRATE_ON_STARTUP:-true}
export MEDIA_ROOT="$DATA_DIR/media"
+export BASEROW_ENABLE_OTEL=${BASEROW_ENABLE_OTEL:-}
+export OTEL_EXPORTER_OTLP_ENDPOINT=${OTEL_EXPORTER_OTLP_ENDPOINT:-}
+export OTEL_RESOURCE_ATTRIBUTES=${OTEL_EXPORTER_OTLP_ENDPOINT:-}
export BASEROW_GROUP_STORAGE_USAGE_ENABLED="${BASEROW_GROUP_STORAGE_USAGE_ENABLED:-}"
export BASEROW_GROUP_STORAGE_USAGE_QUEUE="${BASEROW_GROUP_STORAGE_USAGE_QUEUE:-}"
diff --git a/deploy/otel/otel-collector-config.yaml b/deploy/otel/otel-collector-config.yaml
new file mode 100644
index 0000000000..6decb20ca1
--- /dev/null
+++ b/deploy/otel/otel-collector-config.yaml
@@ -0,0 +1,49 @@
+receivers:
+ otlp:
+ protocols:
+ grpc: # port 4317
+ http: # port 4318
+
+processors:
+ # Disable sending spans for the sync templates task as it contains a huge number
+ # which pointlessly uses up resource limits. Also disable silk spam.
+ filter:
+ traces:
+ span:
+ - 'IsMatch(name, ".*sync_templates_task.*") == true'
+ - 'IsMatch(attributes["db.statement"], ".*silk.*") == true'
+ spanevent:
+ - 'IsMatch(name, ".*sync_templates_task.*") == true'
+ - 'IsMatch(attributes["db.statement"], ".*silk.*") == true'
+ batch:
+ send_batch_size: 1000
+
+exporters:
+ otlp:
+ endpoint: "api.honeycomb.io:443"
+ headers:
+ "x-honeycomb-team": "${env:HONEYCOMB_API_KEY}"
+ otlp/metrics:
+ endpoint: "api.honeycomb.io:443"
+ headers:
+ "x-honeycomb-team": "${env:HONEYCOMB_API_KEY}"
+ "x-honeycomb-dataset": "${env:HONEYCOMB_METRICS_DATASET}"
+ logging:
+
+service:
+ pipelines:
+ traces:
+ receivers: [otlp]
+ processors: [batch]
+ exporters: [otlp,logging]
+ metrics:
+ receivers: [otlp]
+ processors: [batch]
+ exporters: [otlp/metrics,logging]
+ logs:
+ receivers: [otlp]
+ processors: [batch]
+ exporters: [otlp,logging]
+
+extensions:
+ health_check:
\ No newline at end of file
diff --git a/dev.sh b/dev.sh
index 0b54c4f618..72092aa2d6 100755
--- a/dev.sh
+++ b/dev.sh
@@ -359,6 +359,7 @@ if [[ "$dev" = true ]]; then
export PUBLIC_WEB_FRONTEND_URL=${PUBLIC_WEB_FRONTEND_URL:-http://localhost:3000}
export MEDIA_URL=http://localhost:4000/media/
+ export BASEROW_DEPLOYMENT_ENV="development-$USER"
fi
@@ -490,6 +491,7 @@ if [ "$dont_attach" != true ] && [ "$up" = true ] ; then
launch_tab_and_attach "db" "db"
launch_tab_and_attach "redis" "redis"
launch_tab_and_attach "mailhog" "mailhog"
+ launch_tab_and_attach "otel-collector" "otel-collector"
if [ "$dev" = true ] ; then
launch_tab_and_attach "mjml compiler" "mjml-email-compiler"
fi
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 94d406e3a1..b4966529b7 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -23,6 +23,7 @@ services:
- BASEROW_BACKEND_DEBUGGER_ENABLED=${BASEROW_BACKEND_DEBUGGER_ENABLED:-True}
- BASEROW_BACKEND_DEBUGGER_PORT=${BASEROW_BACKEND_DEBUGGER_PORT:-5678}
- BASEROW_DANGEROUS_SILKY_ANALYZE_QUERIES
+ - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
build:
dockerfile: ./backend/Dockerfile
context: .
@@ -43,6 +44,8 @@ services:
# Open stdin and tty so when attaching key input works as expected.
stdin_open: true
tty: true
+ depends_on:
+ - otel-collector
web-frontend:
image: baserow_web-frontend_dev:latest
@@ -81,6 +84,7 @@ services:
GID: $GID
command: "watch-py celery-worker"
environment:
+ - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
- BASEROW_DANGEROUS_SILKY_ANALYZE_QUERIES
volumes:
- ./backend:/baserow/backend
@@ -89,9 +93,14 @@ services:
# Open stdin and tty so when attaching key input works as expected.
stdin_open: true
tty: true
+ depends_on:
+ - otel-collector
celery-export-worker:
image: baserow_backend_dev:latest
+ environment:
+ - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
+ - BASEROW_DANGEROUS_SILKY_ANALYZE_QUERIES
build:
dockerfile: ./backend/Dockerfile
context: .
@@ -102,8 +111,6 @@ services:
UID: $UID
GID: $GID
command: "watch-py celery-exportworker"
- environment:
- - BASEROW_DANGEROUS_SILKY_ANALYZE_QUERIES
volumes:
- ./backend:/baserow/backend
- ./premium/backend/:/baserow/premium/backend
@@ -111,9 +118,13 @@ services:
# Open stdin and tty so when attaching key input works as expected.
stdin_open: true
tty: true
+ depends_on:
+ - otel-collector
celery-beat-worker:
image: baserow_backend_dev:latest
+ environment:
+ - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
build:
dockerfile: ./backend/Dockerfile
context: .
@@ -171,3 +182,16 @@ services:
- caddy_data:/data
networks:
local:
+
+ otel-collector:
+ image: otel/opentelemetry-collector
+ command: [ "--config=/etc/otel-collector-config.yaml" ]
+ environment:
+ HONEYCOMB_API_KEY:
+ HONEYCOMB_METRICS_DATASET: baserow-dev-metrics
+ volumes:
+ - $PWD/deploy/otel/otel-collector-config.yaml:/etc/otel-collector-config.yaml
+ networks:
+ local:
+ ports:
+ - "4318:4318"
diff --git a/docker-compose.local-build.yml b/docker-compose.local-build.yml
index 5e36e703fa..f81f513b5c 100644
--- a/docker-compose.local-build.yml
+++ b/docker-compose.local-build.yml
@@ -71,6 +71,10 @@ x-backend-variables: &backend-variables
BASEROW_BACKEND_DEBUG:
BASEROW_BACKEND_LOG_LEVEL:
FEATURE_FLAGS:
+ BASEROW_ENABLE_OTEL:
+ BASEROW_DEPLOYMENT_ENV:
+ OTEL_EXPORTER_OTLP_ENDPOINT:
+ OTEL_RESOURCE_ATTRIBUTES:
PRIVATE_BACKEND_URL: http://backend:8000
PUBLIC_BACKEND_URL:
@@ -169,6 +173,8 @@ services:
ADDITIONAL_MODULES:
BASEROW_MAX_IMPORT_FILE_SIZE_MB:
BASEROW_MAX_SNAPSHOTS_PER_GROUP:
+ BASEROW_ENABLE_OTEL:
+ BASEROW_DEPLOYMENT_ENV:
depends_on:
- backend
networks:
diff --git a/docker-compose.no-caddy.yml b/docker-compose.no-caddy.yml
index 22ccc07384..67c29ccdc9 100644
--- a/docker-compose.no-caddy.yml
+++ b/docker-compose.no-caddy.yml
@@ -91,6 +91,10 @@ x-backend-variables: &backend-variables
BASEROW_BACKEND_DEBUG:
BASEROW_BACKEND_LOG_LEVEL:
FEATURE_FLAGS:
+ BASEROW_ENABLE_OTEL:
+ BASEROW_DEPLOYMENT_ENV:
+ OTEL_EXPORTER_OTLP_ENDPOINT:
+ OTEL_RESOURCE_ATTRIBUTES:
PRIVATE_BACKEND_URL: http://backend:8000
BASEROW_PUBLIC_URL:
@@ -164,6 +168,8 @@ services:
ADDITIONAL_MODULES:
BASEROW_MAX_IMPORT_FILE_SIZE_MB:
BASEROW_MAX_SNAPSHOTS_PER_GROUP:
+ BASEROW_ENABLE_OTEL:
+ BASEROW_DEPLOYMENT_ENV:
depends_on:
- backend
networks:
diff --git a/docker-compose.yml b/docker-compose.yml
index 5040f6ef8d..d7d030ddb7 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -87,6 +87,10 @@ x-backend-variables: &backend-variables
BASEROW_BACKEND_DEBUG:
BASEROW_BACKEND_LOG_LEVEL:
FEATURE_FLAGS:
+ BASEROW_ENABLE_OTEL:
+ BASEROW_DEPLOYMENT_ENV:
+ OTEL_EXPORTER_OTLP_ENDPOINT:
+ OTEL_RESOURCE_ATTRIBUTES:
PRIVATE_BACKEND_URL: http://backend:8000
PUBLIC_BACKEND_URL:
@@ -181,6 +185,8 @@ services:
ADDITIONAL_MODULES:
BASEROW_MAX_IMPORT_FILE_SIZE_MB:
BASEROW_MAX_SNAPSHOTS_PER_GROUP:
+ BASEROW_ENABLE_OTEL:
+ BASEROW_DEPLOYMENT_ENV:
depends_on:
- backend
networks:
diff --git a/docs/decisions/004-baserow-metrics.md b/docs/decisions/004-baserow-metrics.md
new file mode 100644
index 0000000000..7a53558018
--- /dev/null
+++ b/docs/decisions/004-baserow-metrics.md
@@ -0,0 +1,94 @@
+## The Problem
+
+We want to be able to observe a running instance of Baserow so we can:
+
+1. Understand its performance
+2. Diagnose issues and bugs
+3. Get insights into usage
+
+## Proposed solution
+
+1. We integrate and configure the [opentelemetry](https://opentelemetry.io/) libraries
+ into our applications.
+2. In our codebase we add useful logs, metrics and spans.
+3. Self-hosting users can set a couple of env vars and fully monitor Baserow themselves.
+4. We start using [`loguru`](https://github.com/Delgan/loguru) for all of our Baserow
+ logging and configure with OTEL to
+ ship logs.
+
+### Why [Open Telemetry](https://opentelemetry.io/)?
+
+We could directly integrate with many specific telemetry and cloud monitoring providers.
+However we aren't sure which provider we want to stick with long term. OTEL is the new
+modern way of doing telemetry and you can use it to send telemetry to almost any
+cloud application monitoring platform. By picking a specific provider we would be
+locking ourselves even further into their eco system. By using OTEL we can easily
+switch.
+
+For our self-hosting users, OTEL doesn't force them into a specific
+platform
+but they can monitor Baserow using their existing platform of choice as long as it
+supports OTEL.
+
+OTEL is becoming/already is *the* telemetry standard. It's also completely open source!
+
+### Why loguru?
+
+See https://github.com/Delgan/loguru for details. You will find this library highly
+recommended in lots of places as a great way to do logging in modern python.
+
+We could just configure the existing `logger` python framework to send all of
+it's logs to OTEL. However i'm worried this might send a ton of duplicate
+information or just a massive amount of useless information form all of our libraries
+etc.
+
+By using `loguru` (which has a bunch of other benefits as a more modern and nicer
+to use logging framework for python) we can be sure we are just sending some
+specific Baserow application logs and not a ton of bloat from some libraries.
+
+`loguru` Also supports integrating directly with `logging` if we do want to ship
+some libraries logs very easily.
+
+`loguru` Additionally supports structured logging. We use it to send structured
+logs which aren't just a single line of text, but instead a JSON object with extra
+attributes. This way when structured logging is used (only for sending to OTEL
+collectors, your actual container logs are still readable) we can easily attach
+contextual information to the logs themselves! We can then search for logs which have
+various attributes, like "find me all the logs for group 10, user 5 etc".
+
+#### Example loguru code
+
+This is all we need to do to configure loguru to:
+
+1. Have a lovely coloured output in our normal logs
+2. Send all logs also with extra attributes to our open telemetry collector
+3. Add some attributes to all logging that occurs inside the context:
+
+```python
+from loguru import logger
+
+# A slightly customized default loguru format which includes the process id.
+loguru_format = (
+ f"{os.getpid()}|"
+ "{time:YYYY-MM-DD HH:mm:ss.SSS}|"
+ "{level}|"
+ "{name}:"
+ "{function}:"
+ "{line} - "
+ "{message}"
+)
+
+# Remove the default loguru stderr sink
+logger.remove()
+# Replace it with our format, loguru recommends sending application logs to stderr.
+logger.add(sys.stderr, format=loguru_format)
+logger.info("Logger setup.")
+logger.add(get_otel_handler(), format="{message}")
+logger.info("Logger open telemetry exporting setup.")
+
+
+def run_some_async_task(task):
+ with logger.contextualize(task=task.id):
+ # This log will be enhanced with the task id set by the context call above :)
+ logger.info('Something happened!')
+```
diff --git a/docs/development/metrics-and-logs.md b/docs/development/metrics-and-logs.md
new file mode 100644
index 0000000000..e2acb66ab5
--- /dev/null
+++ b/docs/development/metrics-and-logs.md
@@ -0,0 +1,224 @@
+# Working with metrics and logs as a developer
+
+First see [our monitoring doc](../installation/monitoring.md) for an overview what
+Baserow offers to monitor itself.
+
+This doc explains how to:
+
+1. Setup your dev environment so you can monitor it, find performance
+ issues etc
+2. Add new logs to the codebase and when to do so
+3. What tracing is and how to add new spans tracing your functions
+4. Add new metrics to the codebase and when to do so
+
+## Setting up honeycomb to view Baserow telemetry in your local dev env
+
+1. Sign up at https://honeycomb.io.
+2. Create your own environment inside of honeycomb, you will configure your local dev
+ setup to send events here.
+3. Click on your new environment in the sidebar, click the config icon.
+4. Switch to API keys and copy your API key.
+5. Edit your local `.env` and set:
+
+```bash
+HONEYCOMB_API_KEY=YOUR_KEY
+BASEROW_ENABLE_OTEL=true
+```
+
+6. `./dev.sh restart`
+7. Go to your honeycomb environment and you should start seeing new datasets being
+ created!
+
+### Debugging telemetry
+
+Look at the logs of your otel-collector for a starting place:
+
+```
+docker logs baserow-otel-collector-1
+```
+
+### Under the hood
+
+* `docker-compose.dev.yml` also launches
+ an [Open Telemetry Collector](https://opentelemetry.io/docs/collector/) service
+ configured by the file in `deploy/otel/otel-collector-config.yaml`.
+* When you enable telemetry using `BASEROW_ENABLE_OTEL=true` the dev containers are
+ configured by the
+ `OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318` in `docker-compose.dev.yml`
+ to send telemetry to that local collector.
+* Then this local collector will send telemetry
+ to [honeycomb](https://honeycomb.io) using your `HONEYCOMB_API_KEY` where you can
+ finally inspect everything.
+
+## How to log
+
+To log something just:
+
+```
+from loguru import logger
+
+def application_code():
+ logger.info('something')
+```
+
+See [Loguru's docs](https://github.com/Delgan/loguru) for more information, it has a ton
+of awesome features.
+
+### When and what to log
+
+As of Feb 2023 Baserow doesn't log that much. Now we have a nicer logging framework
+`loguru` and a way of shipping and storing logs using OTEL we should log much more.
+
+1. Log for humans, so they can diagnose what happened in Baserow.
+2. Use the different logging levels available to you error/warning/info/debug/trace.
+3. Don't be afraid of putting into too many logs.
+
+## How add spans to trace requests and method performance
+
+Read [this](https://opentelemetry.io/docs/concepts/observability-primer/#distributed-traces)
+first to understand what a trace and span is and why we want them.
+
+### Tracing a function
+
+You can use the helper decorator `baserow_trace` to wrap a function
+in a span to track it's execution time and other attributes:
+
+```python
+from opentelemetry import trace
+
+tracer = trace.get_tracer(__name__)
+
+
+class SomeClass:
+ @baserow_trace(tracer)
+ def my_func(
+ self
+ ):
+ # do expensive operation we want to track how long it takes
+ pass
+```
+
+`@baserow_trace` will:
+
+1. Wrap the function in a span
+2. Set the span name to the functions module name + the functions qualified name
+ automatically
+3. Catch errors and mark the span as failed and register the exception against the span
+ so it gets sent to the collector.
+
+### Tracing every method in a class
+
+Instead of having to annotate every method in a class with `@baserow_trace` you can
+use the `baserow_trace_methods` function which generates a metaclass that does it for
+you. By default, it will trace all methods in the class not starting with `_`.
+
+`baserow_trace_methods` also supports the `only` and `exclude` parameters which
+let you restrict which exact methods to trace.
+
+```python
+from opentelemetry import trace
+
+tracer = trace.get_tracer(__name__)
+
+
+class SomeClass(metaclass=baserow_trace_methods(tracer)):
+ def a(self):
+ pass
+
+ def b(self):
+ pass
+
+ def c(self):
+ pass
+
+ def d(self):
+ pass
+```
+
+This comes in very useful when working with a class that has abstract methods that
+will be implemented by many sub classes (which we do allot in Baserow).
+
+See below for an example of how to trace every single subclasses implementation of
+`.do` for an abstract base class!
+
+```python
+import abc
+from opentelemetry import trace
+
+tracer = trace.get_tracer(__name__)
+
+
+class ActionType(metaclass=baserow_trace_methods(tracer, abc=True, only='do')):
+ @abc.abstractmethod
+ def do(self):
+ # Every sub class of ActionType will have their `do` method traced!
+ pass
+
+ def b(self):
+ pass
+
+ def c(self):
+ pass
+
+ def d(self):
+ pass
+```
+
+### Adding attributes to the current span
+
+Its often very useful to add attributes to the current span so we can filter and query
+by those later when inspecting the telemetry. We have a simple helper function
+that lets you do this:
+
+```python
+ add_baserow_trace_attrs(
+ attr_you_want_on_the_span=value_you_want,
+ other_attr=other_value
+)
+```
+
+Or you can just use the default OTEL methods:
+
+```python
+ span = get_current_span()
+span.set_attribute(f"baserow.my_span_attr", value)
+```
+
+### Using the OTEL API directly
+
+Remember you can also just manually use
+the [OTEL Python API](https://opentelemetry.io/docs/instrumentation/python/manual/#tracing).
+The helper functions
+shown above are just to help you.
+
+## How to track metrics
+
+You can also keep track of various numerical and statistical metrics using open
+telemetry. We don't provide any helper methods as the otel functions are
+straight-forward.
+Read [this](https://opentelemetry.io/docs/instrumentation/python/manual/#creating-and-using-synchronous-instruments)
+for all of the available types of metrics you can use, but a simple example is shown
+below:
+
+```python
+from opentelemetry import metrics
+
+meter = metrics.get_meter(__name__)
+rows_created_counter = meter.create_counter(
+ "baserow.rows_created",
+ unit="1",
+ description="The number of rows created in user tables.",
+)
+
+def create_row(table):
+ # create some row
+ # keep track of how many have been made!
+ rows_created_counter.add(
+ 1,
+ {
+ "baserow.table_id": table.id,
+ "baserow.database_id": table.database_id,
+ },
+ )
+
+```
\ No newline at end of file
diff --git a/docs/index.md b/docs/index.md
index f32d5a0eef..b92fc94e38 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -44,6 +44,8 @@ Baserow by following one the guides below:
on a fresh Ubuntu install. Please use the guides above instead.
* [Supported runtime dependencies and environments](installation/supported.md): Learn about
the supported and recommended runtime dependencies.
+* [Monitoring Baserow](installation/monitoring.md): Learn how to monitor your Baserow
+ server using open telemetry.
## Baserow Tutorials
@@ -100,6 +102,8 @@ Everything related to contributing and developing for Baserow.
enabling unfinished or unready features.
* [E2E Testing](./development/e2e-testing.md): How to run Baserow's end-to-end tests
and when to add your own.
+* [Metrics and Logs](./development/metrics-and-logs.md): How to work with metrics and logs
+ to aid with monitoring Baserow as a developer.
## Plugins
diff --git a/docs/installation/monitoring.md b/docs/installation/monitoring.md
new file mode 100644
index 0000000000..5bba8298c8
--- /dev/null
+++ b/docs/installation/monitoring.md
@@ -0,0 +1,31 @@
+# Monitoring your Baserow server
+
+Baserow can be configured to ship logs, metrics and traces using
+the [Open Telemetry standard](https://opentelemetry.io/). You can use these to monitor
+your Baserow instance.
+
+Enable this by setting the env var `BASEROW_ENABLE_OTEL=true` and then depending on
+where you want to send telemetry set the
+appropriate [OTEL env vars](https://opentelemetry.io/docs/reference/specification/sdk-environment-variables/#general-sdk-configuration).
+You probably want to set `OTEL_EXPORTER_OTLP_ENDPOINT` also.
+> In our default docker-compose files we have only added passthroughs for the following
+> OTEL specific env vars.
+> * OTEL_EXPORTER_OTLP_ENDPOINT
+> * OTEL_RESOURCE_ATTRIBUTES
+>
+> If you want to use more, you need to edit the compose files
+> yourself and add the env var passthroughs you need.
+
+By default, Baserow will send the following telemetry:
+
+- Baserow application logging.
+- Some basic metrics.
+- Various spans over some of our critical functions and handler methods.
+- Automatic instrumentation provided by OTEL libraries for:
+ - S3 usage by the `botocore` library
+ - SQL queries
+ - Redis queries
+ - HTTP queries
+ - Celery tasks
+ - Django requests/responses
+
diff --git a/enterprise/backend/src/baserow_enterprise/audit_log/job_types.py b/enterprise/backend/src/baserow_enterprise/audit_log/job_types.py
index 88ae675afc..a4ca6fbeb1 100755
--- a/enterprise/backend/src/baserow_enterprise/audit_log/job_types.py
+++ b/enterprise/backend/src/baserow_enterprise/audit_log/job_types.py
@@ -1,4 +1,3 @@
-import logging
from collections import OrderedDict
from typing import Dict
from uuid import uuid4
@@ -11,6 +10,7 @@ from django.utils.translation import override as translation_override
import unicodecsv as csv
from baserow_premium.license.handler import LicenseHandler
+from loguru import logger
from rest_framework import serializers
from baserow.contrib.database.api.export.serializers import (
@@ -30,8 +30,6 @@ from baserow_enterprise.features import AUDIT_LOG
from .models import AuditLogEntry, AuditLogExportJob
-logger = logging.getLogger(__name__)
-
class AuditLogExportJobType(JobType):
type = "audit_log_export"
diff --git a/enterprise/backend/src/baserow_enterprise/features.py b/enterprise/backend/src/baserow_enterprise/features.py
index 082e63ec8a..ba597951d2 100644
--- a/enterprise/backend/src/baserow_enterprise/features.py
+++ b/enterprise/backend/src/baserow_enterprise/features.py
@@ -3,3 +3,4 @@ RBAC = "rbac"
SSO = "sso"
SUPPORT = "support"
AUDIT_LOG = "audit_log"
+METRICS = "metrics"
diff --git a/enterprise/backend/src/baserow_enterprise/sso/oauth2/auth_provider_types.py b/enterprise/backend/src/baserow_enterprise/sso/oauth2/auth_provider_types.py
index 9787d1cece..2e2b61e74b 100644
--- a/enterprise/backend/src/baserow_enterprise/sso/oauth2/auth_provider_types.py
+++ b/enterprise/backend/src/baserow_enterprise/sso/oauth2/auth_provider_types.py
@@ -1,5 +1,4 @@
import json
-import logging
import urllib
from dataclasses import asdict, dataclass
from typing import Any, Dict, Optional, Tuple
@@ -9,6 +8,7 @@ from django.contrib.sessions.backends.base import SessionBase
from django.urls import reverse
import requests
+from loguru import logger
from requests_oauthlib import OAuth2Session
from requests_oauthlib.compliance_fixes import facebook_compliance_fix
@@ -31,9 +31,6 @@ from .models import (
OAUTH_BACKEND_URL = settings.PUBLIC_BACKEND_URL
-logger = logging.getLogger(__name__)
-
-
@dataclass
class WellKnownUrls:
authorization_url: str
diff --git a/enterprise/backend/src/baserow_enterprise/sso/saml/handler.py b/enterprise/backend/src/baserow_enterprise/sso/saml/handler.py
index 5c562f4f0e..c276ada27c 100644
--- a/enterprise/backend/src/baserow_enterprise/sso/saml/handler.py
+++ b/enterprise/backend/src/baserow_enterprise/sso/saml/handler.py
@@ -1,12 +1,12 @@
import base64
import binascii
-import logging
from typing import Any, Dict, Optional
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from defusedxml import ElementTree
+from loguru import logger
from saml2 import BINDING_HTTP_POST, BINDING_HTTP_REDIRECT, entity
from saml2.client import Saml2Client
from saml2.config import Config as Saml2Config
@@ -23,8 +23,6 @@ from .exceptions import (
InvalidSamlResponse,
)
-logger = logging.getLogger(__name__)
-
class SamlAuthProviderHandler:
@classmethod
diff --git a/plugin-boilerplate/{{ cookiecutter.project_slug }}/plugins/{{ cookiecutter.project_module }}/backend/src/{{ cookiecutter.project_module }}/plugins.py b/plugin-boilerplate/{{ cookiecutter.project_slug }}/plugins/{{ cookiecutter.project_module }}/backend/src/{{ cookiecutter.project_module }}/plugins.py
index 1a7d2c5bb5..83cc1e3c31 100644
--- a/plugin-boilerplate/{{ cookiecutter.project_slug }}/plugins/{{ cookiecutter.project_module }}/backend/src/{{ cookiecutter.project_module }}/plugins.py
+++ b/plugin-boilerplate/{{ cookiecutter.project_slug }}/plugins/{{ cookiecutter.project_module }}/backend/src/{{ cookiecutter.project_module }}/plugins.py
@@ -1,11 +1,9 @@
-import logging
+from loguru import logger
from baserow.core.registries import Plugin
from django.urls import path, include
from .api import urls as api_urls
-logger = logging.getLogger(__name__)
-
class PluginNamePlugin(Plugin):
type = "{{ cookiecutter.project_module }}"
diff --git a/premium/backend/src/baserow_premium/api/admin/users/views.py b/premium/backend/src/baserow_premium/api/admin/users/views.py
index d03e5323b7..2f567b1043 100644
--- a/premium/backend/src/baserow_premium/api/admin/users/views.py
+++ b/premium/backend/src/baserow_premium/api/admin/users/views.py
@@ -1,5 +1,3 @@
-import logging
-
from django.contrib.auth import get_user_model
from django.db import transaction
@@ -23,6 +21,7 @@ from baserow_premium.license.features import PREMIUM
from baserow_premium.license.handler import LicenseHandler
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema
+from loguru import logger
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
@@ -37,7 +36,6 @@ from baserow.core.user.utils import generate_session_tokens_for_user
from .serializers import BaserowImpersonateAuthTokenSerializer
-logger = logging.getLogger(__name__)
User = get_user_model()
diff --git a/premium/backend/src/baserow_premium/license/handler.py b/premium/backend/src/baserow_premium/license/handler.py
index 60203cb880..cfd6e8a474 100644
--- a/premium/backend/src/baserow_premium/license/handler.py
+++ b/premium/backend/src/baserow_premium/license/handler.py
@@ -2,7 +2,6 @@ import base64
import binascii
import hashlib
import json
-import logging
from os.path import dirname, join
from typing import Any, Dict, List, Optional, Union
@@ -25,6 +24,7 @@ from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from dateutil import parser
+from loguru import logger
from requests.exceptions import RequestException
from rest_framework.status import HTTP_200_OK
@@ -53,7 +53,6 @@ from .exceptions import (
from .models import LicenseUser
from .registries import license_type_registry
-logger = logging.getLogger(__name__)
User = get_user_model()
diff --git a/premium/backend/src/baserow_premium/license/plugin.py b/premium/backend/src/baserow_premium/license/plugin.py
index a122c2c7c8..59852ed4f6 100644
--- a/premium/backend/src/baserow_premium/license/plugin.py
+++ b/premium/backend/src/baserow_premium/license/plugin.py
@@ -1,4 +1,3 @@
-import logging
from typing import Dict, Generator, Optional, Set
from django.contrib.auth import get_user_model
@@ -9,7 +8,6 @@ from baserow_premium.license.exceptions import InvalidLicenseError
from baserow_premium.license.models import License
from baserow_premium.license.registries import LicenseType
-logger = logging.getLogger(__name__)
User = get_user_model()
diff --git a/web-frontend/docker/docker-entrypoint.sh b/web-frontend/docker/docker-entrypoint.sh
index c68fd4bda8..6b306b375c 100755
--- a/web-frontend/docker/docker-entrypoint.sh
+++ b/web-frontend/docker/docker-entrypoint.sh
@@ -2,6 +2,7 @@
# Bash strict mode: http://redsymbol.net/articles/unofficial-bash-strict-mode/
set -euo pipefail
+export BASEROW_VERSION="1.14.0"
BASEROW_WEBFRONTEND_PORT="${BASEROW_WEBFRONTEND_PORT:-3000}"
show_help() {