Solutions:如何为Python Django应用进行APM

270 阅读1分钟

在今天的这篇文章中,我来简单地介绍如何在Python Django应用框架中实现APM。关于如何安装Elasticsearch, Kibana及APM server,请参阅我之前的文章“应用程序性能监控/管理(APM)实践”。在这篇文章中,我们来简单介绍一下需注意的一些地方。

 

如何配置

我们可以打开Kibaba:

点击上面的Add APM 按钮:

在APM agents里找到Django。我们按照上面的要求来进行配置。如果大家还是不很熟的话,我这里有一个样本的应用:

git clone https://github.com/liu-xiao-guo/weather_app_django

我们按照上面的指令来下载,并查看文件settings.py。下面是这个文件内容的一部分:

settings.py

ELASTIC_APM = {
  # Set required service name. Allowed characters:
  # a-z, A-Z, 0-9, -, _, and space
  'SERVICE_NAME': 'python-django',

  # Use if APM Server requires a token
  'SECRET_TOKEN': '',

  # Set custom APM Server URL (default: http://localhost:8200)
  'SERVER_URL': 'http://localhost:8200',

  'DEBUG': True
}

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_%8&aaez4#5%6)$$#rxdbyv5)(he7(2&@_d77_00tehjkrj$n2'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['localhost', '127.0.0.1']

# Application definition

INSTALLED_APPS = [
    'elasticapm.contrib.django',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'weather'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'elasticapm.contrib.django.middleware.TracingMiddleware'
]

在上面很关键的一点就是:

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['localhost', '127.0.0.1']

我需要把DEBUG设置为false,否则它不会把transaction及error信息发送到APM server。

经过上面的配置后,运行我们的Elasticserch, Kibana及APM server,我们可以看到诸如:

点击python-django:

点击上面的POST weather .views.index: