활동 및 오류 로깅

이 가이드에서는 Workspace Studio 활동 탭에서 실행되지 않는 단계를 해결하는 데 도움이 되는 맞춤 로그 및 오류 메시지를 작성하는 방법을 설명합니다.

기본적으로 활동 탭에는 매니페스트 파일에 정의된 대로 실행되는 단계의 이름이 기록됩니다. 단계 실행 중에 어떤 일이 일어났는지 이해하려면 단계에 대한 맞춤 로그도 작성해야 합니다. 사용자가 단계를 실행하는 동안 예기치 않은 동작이 발생하면 로그를 통해 발생한 상황을 파악할 수 있습니다.

유용한 로그 항목에는 두 가지 속성이 있습니다.

  • 단계에서 생성되거나 업데이트된 리소스에 대한 하이퍼링크가 포함된 칩입니다. 예를 들어 단계에서 Google 문서를 만드는 경우 칩을 사용하여 생성된 Google 문서에 연결합니다.
  • 단계가 실행되지 않은 이유와 문제를 해결하는 방법을 설명하는 자세한 오류 메시지입니다.

다음 코드 샘플은 onExecuteFunctionCreateDocument()가 성공적인 실행과 오류를 활동 탭에 로깅하는 방법을 보여줍니다.

매니페스트 파일은 다음과 같습니다.

JSON

{
  "timeZone": "America/Los_Angeles",
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "addOns": {
    "common": {
      "name": "Log and Error Demo",
      "logoUrl": "https://www.gstatic.com/images/branding/productlogos/gsuite_addons/v6/web-24dp/logo_gsuite_addons_color_1x_web_24dp.png",
      "useLocaleFromApp": true
    },
    "flows": {
      "workflowElements": [
        {
          "id": "log_and_error_demo",
          "state": "ACTIVE",
          "name": "Log and Error Demo",
          "description": "Display a log message when executed successfully, display a error message and retry execution instead.",
          "workflowAction": {
            "inputs": [
              {
                "id": "value1",
                "description": "value1",
                "cardinality": "SINGLE",
                "dataType": {
                  "basicType": "INTEGER"
                }
              }
            ],
            "outputs": [
              {
                "id": "result",
                "description": "execution result",
                "cardinality": "SINGLE",
                "dataType": {
                  "basicType": "STRING"
                }
              }
            ],
            "onConfigFunction": "onConfigFunctionCreateDocument",
            "onExecuteFunction": "onExecuteFunctionCreateDocument"
          }
        }
      ]
    }
  }
}

다음은 애플리케이션 로직 코드입니다.

Apps Script

function onConfigFunctionCreateDocument() {
  const firstInput = CardService.newTextInput()
    .setFieldName("value1")
    .setTitle("First Value") //"FieldName" must match an "id" in the manifest file's inputs[] array.
    .setHint("Input 1 to successfully execute the step, 0 to fail the step and return an error.")
    .setHostAppDataSource(
      CardService.newHostAppDataSource()
        .setWorkflowDataSource(
          CardService.newWorkflowDataSource()
            .setIncludeVariables(true)
        )
    );

  let cardSection = CardService.newCardSection()
    .addWidget(firstInput);

  return CardService.newCardBuilder()
    .addSection(cardSection)
    .build();
}

function onExecuteFunctionCreateDocument(event) {

  // true if the document is successfully created, false if something goes wrong.
  var successfulRun = event.workflow.actionInvocation.inputs["value1"].integerValues[0];
  console.log("The user input is: ", successfulRun);

  // If successful, return an activity log linking to the created document.
  if (successfulRun == 1) {
    let logChip = AddOnsResponseService.newTextFormatChip()
      .setTextFormatIcon(
        AddOnsResponseService.newTextFormatIcon()
          .setMaterialIconName("edit_document")
      )
      .setUrl("https://docs.google.com/document/d/{DOCUMENT}")
      .setLabel("Mock Document");

    let output = AddOnsResponseService.newVariableData()
      .addStringValue("Created Google Doc");

    const workflowAction = AddOnsResponseService.newReturnOutputVariablesAction()
      .addVariableData("result", output)
      // Set the user-facing error log
      .setLog(
        AddOnsResponseService.newWorkflowTextFormat()
          .addTextFormatElement(
            AddOnsResponseService.newTextFormatElement()
              .setText("Created Google Doc")
          )
          .addTextFormatElement(
            AddOnsResponseService.newTextFormatElement()
              .setTextFormatChip(logChip)
          )
          .addTextFormatElement(
            AddOnsResponseService.newTextFormatElement()
              .setText("Created doc detailing how to improve product.")
          )
      );

    let hostAppAction = AddOnsResponseService.newHostAppAction()
      .setWorkflowAction(workflowAction);

    return AddOnsResponseService.newRenderActionBuilder()
      .setHostAppAction(hostAppAction)
      .build();
  }
  // Otherwise, return an activity log containing an error explaining what happened and how to resolve the issue.
  else {
    let errorChip = AddOnsResponseService.newTextFormatChip()
      .setTextFormatIcon(
        AddOnsResponseService.newTextFormatIcon()
          .setMaterialIconName("file_open")
      )
      .setLabel("Mock Document");

    const workflowAction = AddOnsResponseService.newReturnElementErrorAction()
      .setErrorActionability(AddOnsResponseService.ErrorActionability.ACTIONABLE)
      .setErrorRetryability(AddOnsResponseService.ErrorRetryability.NOT_RETRYABLE)
      // Set the user-facing error log
      .setErrorLog(
        AddOnsResponseService.newWorkflowTextFormat()
          .addTextFormatElement(
            AddOnsResponseService.newTextFormatElement()
              .setText("Failed to create Google Doc.")
          )
          .addTextFormatElement(
            AddOnsResponseService.newTextFormatElement()
              .setTextFormatChip(errorChip)
          )
          .addTextFormatElement(
            AddOnsResponseService.newTextFormatElement()
              .setText("Unable to create Google Document because OAuth verification failed. Grant one of these authorization scopes and try again: https://www.googleapis.com/auth/documents, \nhttps://www.googleapis.com/auth/drive, \nhttps://www.googleapis.com/auth/drive.file")
          )
      );

    let hostAppAction = AddOnsResponseService.newHostAppAction()
      .setWorkflowAction(workflowAction);

    return AddOnsResponseService.newRenderActionBuilder()
      .setHostAppAction(hostAppAction)
      .build();
  }
}