IT박스

Google Analytics analytics.js 예외 추적에서 예외보고

itboxs 2020. 10. 26. 07:49
반응형

Google Analytics analytics.js 예외 추적에서 예외보고


Google 유니버설 애널리틱스에는 조회 유형 예외가 있습니다.

ga('send', 'exception', {
  'exDescription': 'DatabaseError'
});

Google Analytics 콘솔로 이동하여 '이벤트'와 동일한 수준의 예외 보고서를 찾을 수있을 것으로 기대했지만 볼 수있는 곳이 없습니다.

Android 및 iOS API에 따르면 Crash and exception data is available primarily in the Crash and Exceptions report해당 이름으로 보고서를 찾을 수 없습니다.


그것을 알아 냈습니다. 왜 그들이 이것을 내장 된 보고서로 만들지 않는지 모르겠지만 언젠가는 아마 모르겠습니다.

Exception Description차원 에 대한 대시 보드와 메트릭에 대한 'Crashes'를 사용하여 사용자 정의 위젯을 만들었습니다 .

여기에 이미지 설명 입력

다음과 같은 보고서를 제공합니다.

여기에 이미지 설명 입력

Customization탭으로 이동하여 오류 표를 제공하는 사용자 지정 보고서를 만든 다음 대시 보드에 추가 할 수도 있습니다.

여기에 이미지 설명 입력

이 전역 예외 처리기와 함께 사용

if (typeof window.onerror == "object")
{
    window.onerror = function (err, url, line)
    {
        if (ga) 
        {
           ga('send', 'exception', {
               'exDescription': line + " " + err
           });
        }
    };
}

이 핸들러는 자바 스크립트 초기화의 어느 곳에 나 배치 할 수 있습니다. 이는 모든 JS 파일을 어떻게 구성했는지에 따라 달라집니다. 또는 <script>html body 태그 상단 근처의 태그 안에 넣을 수도 있습니다 .


Simon_Weaver의 가이드를 통해 맞춤 보고서를 몇 단계 더 발전 시켰고 상당히 완전한 Google Analytics 맞춤 예외 보고서를 작성했습니다. 공유 할 가치가있을 것 같아서 GA "솔루션 갤러리"에 업로드했습니다.

내 템플릿 : Google Analytics 예외 보고서

다음은 최종 결과의 그림입니다.

https://imgur.com/a/1UYIzrZ


몇 가지 추가 세부 정보와 함께 오류 보고서를 제공하기 위해 @Simon_Weaver의 훌륭한 답변에 대해 약간 확장하고 싶었습니다.

  • ga()호출을 시도하기 전에이 정의되어 있는지 확인하십시오 (분석 라이브러리가로드되기 전에 오류가 트리거 될 수 있음).
  • Analytics 보고서에 예외 줄 번호 및 열 인덱스를 기록합니다 (프로덕션에 사용되는 축소 된 JavaScript 코드는 읽기 어려울 수 있음).
  • 이전에 정의 된 window.onerror콜백을 실행합니다 .
/**
 * Send JavaScript error information to Google Analytics.
 * 
 * @param  {Window} window A reference to the "window".
 * @return {void}
 * @author Philippe Sawicki <https://github.com/philsawicki>
 */
(function (window) {
    // Retain a reference to the previous global error handler, in case it has been set:
    var originalWindowErrorCallback = window.onerror;

    /**
     * Log any script error to Google Analytics.
     *
     * Third-party scripts without CORS will only provide "Script Error." as an error message.
     * 
     * @param  {String}           errorMessage Error message.
     * @param  {String}           url          URL where error was raised.
     * @param  {Number}           lineNumber   Line number where error was raised.
     * @param  {Number|undefined} columnNumber Column number for the line where the error occurred.
     * @param  {Object|undefined} errorObject  Error Object.
     * @return {Boolean}                       When the function returns true, this prevents the 
     *                                         firing of the default event handler.
     */
    window.onerror = function customErrorHandler (errorMessage, url, lineNumber, columnNumber, errorObject) {
        // Send error details to Google Analytics, if the library is already available:
        if (typeof ga === 'function') {
            // In case the "errorObject" is available, use its data, else fallback 
            // on the default "errorMessage" provided:
            var exceptionDescription = errorMessage;
            if (typeof errorObject !== 'undefined' && typeof errorObject.message !== 'undefined') {
                exceptionDescription = errorObject.message;
            }

            // Format the message to log to Analytics (might also use "errorObject.stack" if defined):
            exceptionDescription += ' @ ' + url + ':' + lineNumber + ':' + columnNumber;

            ga('send', 'exception', {
                'exDescription': exceptionDescription,
                'exFatal': false, // Some Error types might be considered as fatal.
                'appName': 'Application_Name',
                'appVersion': '1.0'
            });
        }

        // If the previous "window.onerror" callback can be called, pass it the data:
        if (typeof originalWindowErrorCallback === 'function') {
            return originalWindowErrorCallback(errorMessage, url, lineNumber, columnNumber, errorObject);
        }
        // Otherwise, Let the default handler run:
        return false;
    };
})(window);

// Generate an error, for demonstration purposes:
//throw new Error('Crash!');

편집 : @Simon_Weaver가 정식으로 언급했듯이 Google Analytics에는 이제 예외 추적에 대한 문서가 있습니다 (원래 답변에서 링크 했어야 함-죄송합니다, 신인 실수입니다!).


이것이 제가 생각해 낸 것이므로 모든 곳에 코드를 포함 할 필요가 없습니다. new ErrorHandler();각 .js 파일에 추가 하기 만하면 됩니다. 이것은 Chrome 확장 프로그램을 위해 수행되었지만 어디서나 작동해야한다고 생각합니다. 실제 ga () 항목을 별도의 파일 (따라서 app.GA)에 구현하지만 여기에서도 구울 수 있습니다.

/*
 *  Copyright (c) 2015-2017, Michael A. Updike All rights reserved.
 *  Licensed under the BSD-3-Clause
 *  https://opensource.org/licenses/BSD-3-Clause
 *  https://github.com/opus1269/photo-screen-saver/blob/master/LICENSE.md
 */
// noinspection ThisExpressionReferencesGlobalObjectJS
(function(window, factory) {
    window.ExceptionHandler = factory(window);
}(this, function(window) {
    'use strict';

    return ExceptionHandler;

    /**
     * Log Exceptions with analytics. Include: new ExceptionHandler();<br />
     * at top of every js file
     * @constructor
     * @alias ExceptionHandler
     */
    function ExceptionHandler() {
        if (typeof window.onerror === 'object') {
            // global error handler
            window.onerror = function(message, url, line, col, errObject) {
                if (app && app.GA) {
                    let msg = message;
                    let stack = null;
                    if (errObject && errObject.message && errObject.stack) {
                        msg = errObject.message;
                        stack = errObject.stack;
                    }
                    app.GA.exception(msg, stack);
                }
            };
        }
    }
}));

이제 동작에서 '비정상 종료 및 예외'보기를 찾을 수 있습니다 (Google 애널리틱스에서 속성이 '모바일 앱'으로 생성 된 경우).

2018 년 5 월 현재 Google Analytics의 사이드 메뉴

참고 URL : https://stackoverflow.com/questions/21718481/report-for-exceptions-from-google-analytics-analytics-js-exception-tracking

반응형