programing tip

Google Apps Script를 디버깅하는 방법 (일명 Logger.log는 어디에 기록됩니까?)

itbloger 2020. 8. 4. 07:48
반응형

Google Apps Script를 디버깅하는 방법 (일명 Logger.log는 어디에 기록됩니까?)


Google 스프레드 시트에서 일부 스크립팅 기능을 추가 할 수 있습니다. onEdit이벤트를 위해 무언가를 추가하고 있지만 이벤트가 작동하는지 알 수 없습니다. 내가 알 수있는 한 Google 스프레드 시트에서 라이브 이벤트를 디버깅 할 수 없으므로 디버거에서 수행해야합니다. 디버거에서 수행해야합니다. 내 onEdit()함수에 전달 된 이벤트 인수가 이벤트 에서 실행되면 항상 정의되지 않기 때문에 의미가 없습니다. Script Editor.

그래서 함수를 호출 Logger.log할 때마다 메소드 를 사용하여 일부 데이터를 기록 하려고 시도 onEdit했지만 이것도에서 실행될 때만 작동하는 것처럼 보입니다 Script Editor. 에서 실행하면 Script Editor로 이동하여 로그를 볼 수 있습니다View->Logs...

이벤트가 실제로 실행될 때의 로그를 볼 수 있기를 바랐지만 이해할 수 없었습니다.

이 물건을 어떻게 디버깅합니까?


최신 정보:

답변에 쓰여진 것처럼


Logger.log스크립트에서 발생한 오류에 대한 전자 메일을 보내거나 (또는 ​​최종적으로)에서 실행중인 경우 (아직 스크립트 편집기에서) Script Editor로 이동하여 마지막 실행 기능의 로그를 볼 수 있습니다 View->Logs. 다시 말하지만, 내부에서Script Editor 마지막으로 실행 함수에서 기록 된 내용 만 표시 됩니다 .

내가 작업하려고했던 스크립트는 스프레드 시트와 관련이있었습니다. 항목을 우선 순위별로 정렬하는 스프레드 시트 todo-checklist 유형을 만들었습니다.

해당 스크립트에 대해 설치 한 유일한 트리거는 onOpen 및 onEdit 트리거입니다. onEdit 트리거를 디버깅하는 것이 가장 어려웠습니다. onEdit 함수에서 중단 점을 설정하면 스프레드 시트가 열리고 셀이 편집되어 중단 점이 트리거 될 것이라고 생각했기 때문에 계속 생각했습니다. 그렇지 않다.

셀을 편집 한 시뮬레이션하기 위해, 나는 않았다 하지만 실제 스프레드 시트에서 무언가를하는 것을 끝낸다. 내가 "편집 된"것으로 취급하기를 원하는 셀이 선택되어 있는지 확인한 다음에로 Script Editor이동했습니다 Run->onEdit. 그런 다음 내 중단 점이 발생합니다.

그러나 onEdit 함수에 전달되는 이벤트 인수 사용을 중지해야했습니다 Run->onEdit. 를 수행하여 시뮬레이션 할 수는 없습니다 . 선택한 셀과 같은 스프레드 시트에서 필요한 모든 정보는 수동으로 파악해야했습니다.

어쨌든 긴 대답이지만 결국 알아 냈습니다.


편집 :

내가 만든 할일 체크리스트를 보려면 여기에서 확인할 수 있습니다

(예, 누구나 편집 할 수 있음을 알고 있습니다. 공유하는 것이 중요합니다!)

스크립트를 볼 수 있기를 바랐습니다. 거기에서 볼 수 없으므로 여기 있습니다.

function onOpen() {
  setCheckboxes();
};

function setCheckboxes() {
  var checklist = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("checklist");
  var checklist_data_range = checklist.getDataRange();
  var checklist_num_rows = checklist_data_range.getNumRows();
  Logger.log("checklist num rows: " + checklist_num_rows);

  var coredata = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("core_data");
  var coredata_data_range = coredata.getDataRange();

  for(var i = 0 ; i < checklist_num_rows-1; i++) {
    var split = checklist_data_range.getCell(i+2, 3).getValue().split(" || ");
    var item_id = split[split.length - 1];
    if(item_id != "") {
      item_id = parseInt(item_id);
      Logger.log("setting value at ("+(i+2)+",2) to " + coredata_data_range.getCell(item_id+1, 3).getValue());
      checklist_data_range.getCell(i+2,2).setValue(coredata_data_range.getCell(item_id+1, 3).getValue());
    }
  }
}

function onEdit() {
  Logger.log("TESTING TESTING ON EDIT");
  var active_sheet = SpreadsheetApp.getActiveSheet();
  if(active_sheet.getName() == "checklist") {
    var active_range = SpreadsheetApp.getActiveSheet().getActiveRange();
    Logger.log("active_range: " + active_range);
    Logger.log("active range col: " + active_range.getColumn() + "active range row: " + active_range.getRow());
    Logger.log("active_range.value: " + active_range.getCell(1, 1).getValue());
    Logger.log("active_range. colidx: " + active_range.getColumnIndex());
    if(active_range.getCell(1,1).getValue() == "?" || active_range.getCell(1,1).getValue() == "?") {
      Logger.log("made it!");
      var next_cell = active_sheet.getRange(active_range.getRow(), active_range.getColumn()+1, 1, 1).getCell(1,1);
      var val = next_cell.getValue();
      Logger.log("val: " + val);
      var splits = val.split(" || ");
      var item_id = splits[splits.length-1];
      Logger.log("item_id: " + item_id);

      var core_data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("core_data");
      var sheet_data_range = core_data.getDataRange();
      var num_rows = sheet_data_range.getNumRows();
      var sheet_values = sheet_data_range.getValues();
      Logger.log("num_rows: " + num_rows);

      for(var i = 0; i < num_rows; i++) {
        Logger.log("sheet_values[" + (i) + "][" + (8) + "] = " + sheet_values[i][8]);
        if(sheet_values[i][8] == item_id) {
          Logger.log("found it! tyring to set it...");
          sheet_data_range.getCell(i+1, 2+1).setValue(active_range.getCell(1,1).getValue());
        }
      }

    }
  }

  setCheckboxes();
};

내가 알 수있는 한, Google 문서에서 라이브 이벤트를 디버깅 할 수 없으므로 디버거에서 수행해야합니다. 내 onEdit () 함수에 전달 된 이벤트 인수가 실행되면 항상 정의되지 않기 때문에 의미가 없습니다. 스크립트 편집기에서

True - so define the event argument yourself for debugging. See How can I test a trigger function in GAS?

I was trying to use the Logger.log method to log some data whenever the onEdit function gets called, but this too seems like it only works when run from the Script Editor. When I run it from the Script Editor, I can view the logs by going to View->Logs...

True again, but there is help. Peter Hermann's BetterLog library will redirect all logs to a spreadsheet, enabling logging even from code that is not attached to an instance of the editor / debugger.

If you're coding in a spreadsheet-contained script, for example, you can add just this one line to the top of your script file, and all logs will go to a "Logs" sheet in the spreadsheet. No other code necessary, just use Logger.log() as you usually would:

Logger = BetterLog.useSpreadsheet();

2017 Update: Stackdriver Logging is now available for Google Apps Script. From the menu bar in the script editor, goto: View > Stackdriver Logging to view or stream the logs.

console.log() will write DEBUG level messages

Example onEdit() logging:

function onEdit (e) {
  var debug_e = {
    authMode:  e.authMode,  
    range:  e.range.getA1Notation(),    
    source:  e.source.getId(),
    user:  e.user,   
    value:  e.value,
    oldValue: e. oldValue
  }

  console.log({message: 'onEdit() Event Object', eventObject: debug_e});
}

Then check the logs in the Stackdriver UI labeled onEdit() Event Object to see the output


A little hacky, but I created an array called "console", and anytime I wanted to output to console I pushed to the array. Then whenever I wanted to see the actual output, I just returned console instead of whatever I was returning before.

    //return 'console' //uncomment to output console
    return "actual output";
}

If you have the script editor open you will see the logs under View->Logs. If your script has an onedit trigger, make a change to the spreadsheet which should trigger the function with the script editor opened in a second tab. Then go to the script editor tab and open the log. You will see whatever your function passes to the logger.

Basically as long as the script editor is open, the event will write to the log and show it for you. It will not show if someone else is in the file elsewhere.


I am having the same problem, I found the below on the web somewhere....

Event handlers in Docs are a little tricky though. Because docs can handle multiple simultaneous edits by multiple users, the event handlers are handled server-side. The major issue with this structure is that when an event trigger script fails, it fails on the server. If you want to see the debug info you'll need to setup an explicit trigger under the triggers menu that emails you the debug info when the event fails or else it will fail silently.


It's far from elegant, but while debugging, I often log to the Logger, and then use getLog() to fetch its contents. Then, I either:

  • save the results to a variable (which can be inspected in the Google Scripts debugger—this works around cases where I can't set a breakpoint in some code, but I can set one in code that gets executed later)
  • write it to some temporary DOM element
  • display it in an alert

Essentially, it just becomes a JavaScript output issue.

It grossly lacks the functionality of modern console.log() implementations, but the Logger does still help debug Google Scripts.


just debug your spreadsheet code like this:

...
throw whatAmI;
...

shows like this:

enter image description here


Currently you are confined to the container bound nature of using scripts within docs. If you create a new script inside outside of docs then you will be able to export information to a google spreadsheet and use it like a logging tool.

For example in your first code block

function setCheckboxes() {

    // Add your spreadsheet data
    var errorSheet = SpreadsheetApp.openById('EnterSpreadSheetIDHere').getSheetByName('EnterSheetNameHere');
    var cell = errorSheet.getRange('A1').offset(errorSheet.getLastRow(),0);

    // existing code
    var checklist = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("checklist");
    var checklist_data_range = checklist.getDataRange();
    var checklist_num_rows = checklist_data_range.getNumRows();

    // existing logger
    Logger.log("checklist num rows: " + checklist_num_rows);

   //We can pass the information to the sheet using cell.setValue()
    cell.setValue(new Date() + "Checklist num rows: " + checklist_num_rows);

When I'm working with GAS I have two monitors ( you can use two windows ) set up with one containing the GAS environment and the other containing the SS so I can write information to and log.


Just as a notice. I made a test function for my spreadsheet. I use the variable google throws in the onEdit(e) function (I called it e). Then I made a test function like this:

function test(){
var testRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GetItemInfoSheetName).getRange(2,7)
var testObject = {
    range:testRange,
    value:"someValue"
}
onEdit(testObject)
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GetItemInfoSheetName).getRange(2,6).setValue(Logger.getLog())
}

Calling this test function makes all the code run as you had an event in the spreadsheet. I just put in the possision of the cell i edited whitch gave me an unexpected result, setting value as the value i put into the cell. OBS! for more variables googles gives to the function go here: https://developers.google.com/apps-script/guides/triggers/events#google_sheets_events


The dev console will log errors thrown by the app script, so you can just throw an error to get it logged as a normal console.log. It will stop execution, but it might still be useful for step by step debugging.

throw Error('hello world!');

will show up in the console similarly to console.log('hello world')

참고URL : https://stackoverflow.com/questions/11539411/how-to-debug-google-apps-script-aka-where-does-logger-log-log-to

반응형