Bagaimana mengelola pelaporan kesalahanLink to this heading

Ketika anda sedang menjalankan situs umum anda harus selalu mematikan pengaturan DEBUG. Itu akan membuat peladen anda berjalan lebih cepat, dan juga akan mencegah pengguna hahat dari melihat rincian dari aplikasi anda yang dapat diungkap dengan kesalahan halaman.

However, running with DEBUG set to False means you'll never see errors generated by your site -- everyone will instead see your public error pages. You need to keep track of errors that occur in deployed sites, so Django can be configured to create reports with details about those errors.

Surel laporanLink to this heading

Kesalahan peladenLink to this heading

When DEBUG is False, Django will email the users listed in the ADMINS setting whenever your code raises an unhandled exception and results in an internal server error (strictly speaking, for any response with an HTTP status code of 500 or greater). This gives the administrators immediate notification of any errors. The ADMINS will get a description of the error, a complete Python traceback, and details about the HTTP request that caused the error.

Secara awal, Django akan mengirim surel dari root@localhost. Bagaimanapun, beberapa penyedia surat menolak semua surel dari alamat ini. Untuk menggunakan alamat pengirim berbeda, rubah pengaturan SERVER_EMAIL.

Untuk mengaktifkan perilaku ini, masukkan alamat surel dari penerima di bagian ADMINS.

kesalahan 404Link to this heading

Django juga dapat dikonfirgasi untuk mengirimkan surel kesalahan tentang tautan yang tidak ditemukan (404 "page not found" errors). Django mengirim surel tentang error 404 ketika:

If those conditions are met, Django will email the users listed in the MANAGERS setting whenever your code raises a 404 and the request has a referer. It doesn't bother to email for 404s that don't have a referer -- those are usually people typing in broken URLs or broken web bots. It also ignores 404s when the referer is equal to the requested URL, since this behavior is from broken web bots too.

Anda dapat memberitahu Django untuk menghentikan pelaporan tertentu 404 dengan merubah pengaturan IGNORABLE_404_URLS. Dia harus menjadi daftar dari obyek ungkapan biasa tersusun. Sebagai contoh:

Code
import re

IGNORABLE_404_URLS = [
    re.compile(r"\.(php|cgi)$"),
    re.compile(r"^/phpmyadmin/"),
]

Dalam contoh ini, sebuah 404 pada setiap URL berakhiran dengan .php atau .cgi akan tidak dilaporkan. Juga tidak akan URL apapun dimulai dengan /phpmyadmin/.

Contoh berikut menunjukkan bagaimana mengeluarkan beberapa URL biasa yang perambah dan penjilat sering diminta:

Code
import re

IGNORABLE_404_URLS = [
    re.compile(r"^/apple-touch-icon.*\.png$"),
    re.compile(r"^/favicon\.ico$"),
    re.compile(r"^/robots\.txt$"),
]

(Perhatikan bahwa ini adalah regular expression, jadi kita tuliskan garis miring terbalik di depan titik untuk melepaskannya)

Jika anda suka menyesuaikan perilaku dari django.middleware.common.BrokenLinkEmailsMiddleware lebih lanjut (sebagai contoh untuk mengabaikan permintaan datang dari penjilat jaringan), anda harus mensubkelaskannya dan menimpa caranya.

Menyaring laporan kesalahanLink to this heading

Menyaring informasi rahasiaLink to this heading

Laporan kesalahan sangat membantu untuk memeriksa kesalahan, jadi dia umumnya berguna untuk merekam informasi terkait tentang kesalahan-kesalahan tersebut sebanyak mungkin. Sebagai contoh, secara awal rekaman Django full traceback untuk dimunculkan pengecualian, setiap variabel lokal full traceback, dan attributes HttpRequest.

Bagaimanapun, terkadang jenis-jenis informasi tertentu mungkin terlalu sensitif dan dengan demikian mungkin tidak sesuai untuk terus melacak, sebagai contoh, sandi pengguna atau angka kartu kredit. Jadi di tambahaan untuk menyaring pengaturan yang muncul menjadi sensitif seperti digambarkan dalam dokumentasi DEBUG, Django menawarkan sekumpulan fungsi penghias untuk membantu anda mengendalikan informasi mana harus disaring dari laporan kesalahan dalam lingkungan produksi (yaitu, dimana DEBUG disetel ke False): sensitive_variables() dan sensitive_post_parameters().

sensitive_variables(*variables)Link to this definition

Jika sebuah fungsi (baik sebuah tampilan atau callback umum apapun) dalam kode anda menggunakan variabel lokal rentan mengandung informasi sensitif, anda mungkin mencegah nilai-nilai variabel tersebut dari menjadi disertakan dalam laporan kesalahan menggunakan penghias sensitive_variables:

Code
from django.views.decorators.debug import sensitive_variables


@sensitive_variables("user", "pw", "cc")
def process_info(user):
    pw = user.pass_word
    cc = user.credit_card_number
    name = user.name
    ...

In the above example, the values for the user, pw and cc variables will be hidden and replaced with stars (**********) in the error reports, whereas the value of the name variable will be disclosed.

Untuk secara sistematis menyembunyikan semua variabel lokal dari sebuah fungsi dari laporan kesalahan, jangan menyediakan argumen apapun pada decorator sensitive_variables:

Code
@sensitive_variables()
def my_function():
    ...
sensitive_post_parameters(*parameters)Link to this definition

Jika satu dari tampilan anda menerima sebuah obyek HttpRequest dengan POST parameters rentan untuk mengandung informasi sensitif, anda mungkin mencegah nilai-nilai dari parameter tersebut dari menjadi disertakan dalam laporan kesalahan menggunakan penghias sensitive_post_parameters:

Code
from django.views.decorators.debug import sensitive_post_parameters


@sensitive_post_parameters("pass_word", "credit_card_number")
def record_user_profile(request):
    UserProfile.create(
        user=request.user,
        password=request.POST["pass_word"],
        credit_card=request.POST["credit_card_number"],
        name=request.POST["name"],
    )
    ...

In the above example, the values for the pass_word and credit_card_number POST parameters will be hidden and replaced with stars (**********) in the request's representation inside the error reports, whereas the value of the name parameter will be disclosed.

Untuk secara sistematis menyembunyikan semua parameter POST dari sebuah permintaan dalam laporan kesalahan, jangan menyediakan argumen apapun pada decorator sensitive_variables:

Code
@sensitive_post_parameters()
def my_view(request):
    ...

Semua parameter POST adalah sistematis disaring keluar dari laporan kesalahan untuk tampilan django.contrib.auth.views tertentu (login, password_reset_confirm, password_change, dan add_view dan user_change_password dalam admin auth) untuk mencegah dari pembocoran dari informasi sensitif seperti sandi pengguna.

Penyesuaian laporan kesalahanLink to this heading

All sensitive_variables() and sensitive_post_parameters() do is, respectively, annotate the decorated function with the names of sensitive variables and annotate the HttpRequest object with the names of sensitive POST parameters, so that this sensitive information can later be filtered out of reports when an error occurs. The actual filtering is done by Django's default error reporter filter: django.views.debug.SafeExceptionReporterFilter. This filter uses the decorators' annotations to replace the corresponding values with stars (**********) when the error reports are produced. If you wish to override or customize this default behavior for your entire site, you need to define your own filter class and tell Django to use it via the DEFAULT_EXCEPTION_REPORTER_FILTER setting:

Code
DEFAULT_EXCEPTION_REPORTER_FILTER = "path.to.your.CustomExceptionReporterFilter"

Anda dapat juga mengendalikan cara lebih kecil penyaring mana untuk digunakan dalam tampilan yang diberikan oleh pengaturan atribut exception_reporter_filter HttpRequest:

Code
def my_view(request):
    if request.user.is_authenticated:
        request.exception_reporter_filter = CustomExceptionReporterFilter()
    ...

Kelas saringan penyesuaian anda perlu mewarisi dari django.views.debug.SafeExceptionReporterFilter dan mungkin menimpa atribut dan metode berikut:

class SafeExceptionReporterFilterLink to this definition
cleansed_substituteLink to this definition

Nilai string untuk mengganti nilai sensitif. Secara awalan itu mengganti nilai dari variabel sensitif dengan bintang (**********).

hidden_settingsLink to this definition

Sebuah obyek regular expression tersusun digunakan untuk mencocokkan pengaturan dan nilai request.META yang dianggap sensitif. Secara awalan setara pada:

Code
import re

re.compile(r"API|TOKEN|KEY|SECRET|PASS|SIGNATURE|HTTP_COOKIE", flags=re.IGNORECASE)
is_active(request)Link to this definition

Returns True to activate the filtering in get_post_parameters() and get_traceback_frame_variables(). By default the filter is active if DEBUG is False. Note that sensitive request.META values are always filtered along with sensitive setting values, as described in the DEBUG documentation.

get_post_parameters(request)Link to this definition

Mengembalikan dictionary yang disaring dari parameter POST. Nilai sensitif diganti dengan cleansed_substitute.

get_traceback_frame_variables(request, tb_frame)Link to this definition

Mengembalikan dictionary yang disaring dari variabel lokal untuk untuk kerangka traceback yang diberikan. Nilai sensitif diganti dengan cleansed_substitute.

Jika anda butuh menyesuaikan laporan kesalahan melampaui penyaringan anda mungkin menentukan kelas pelapor kesalahan disesuaikan dengan menentukan pengaturan DEFAULT_EXCEPTION_REPORTER.

Code
DEFAULT_EXCEPTION_REPORTER = "path.to.your.CustomExceptionReporter"

The exception reporter is responsible for compiling the exception report data, and formatting it as text or HTML appropriately. (The exception reporter uses DEFAULT_EXCEPTION_REPORTER_FILTER when preparing the exception report data.)

Kelas pelapor disesuaikan anda butuh diwarisi dari django.views.debug.ExceptionReporter.

class ExceptionReporterLink to this definition
html_template_pathLink to this definition

Property that returns a pathlib.Path representing the absolute filesystem path to a template for rendering the HTML representation of the exception. Defaults to the Django provided template.

text_template_pathLink to this definition

Property that returns a pathlib.Path representing the absolute filesystem path to a template for rendering the plain-text representation of the exception. Defaults to the Django provided template.

get_traceback_data()Link to this definition

Mengembalikan sebuah dictionary menanggung informasi melacak kembali.

Ini adalah titik ekstensi utama untuk menyesuaikan laporan pengecualian, sebagai contoh:

Code
from django.views.debug import ExceptionReporter


class CustomExceptionReporter(ExceptionReporter):
    def get_traceback_data(self):
        data = super().get_traceback_data()
        # ... remove/add something here ...
        return data
get_traceback_html()Link to this definition

Mengembalikan versi HTML dari laporan pengecualian.

Digunakan untuk versi HTML dari pengawakutu halaman kesalahan HTTP 500.

get_traceback_text()Link to this definition

Mengembalikan versi teks polis dari laporan pengecualian.

Digunakan untuk versi teks polos dari pengawakutu halaman kesalahan HTTP 500 dan laporan surel.

As with the filter class, you may control which exception reporter class to use within any given view by setting the HttpRequest’s exception_reporter_class attribute:

Code
def my_view(request):
    if request.user.is_authenticated:
        request.exception_reporter_class = CustomExceptionReporter()
    ...