[英]Google Cloud Logging API with Apps Script - delete logs - The requested URL was not found on this server
使用 Apps 腳本,我需要刪除特定 Google Cloud 項目的 Stackdriver 日志。 這應該可以通過 Apps 腳本和 Cloud Logging REST API 使用DELETE
請求來實現。 Apps 腳本UrlFetchApp.fetch(url,options)
可以使用DELETE
方法。 下面的代碼返回響應代碼:404。我之前得到響應代碼:400,但現在它接受了 URL 結構,但它找不到 URL。 如果 URL 需要日志 ID,那么我不確定從哪里獲取日志 ID。 我想刪除項目中的所有日志,而不僅僅是一個特定的。
錯誤信息:
The requested URL was not found on this server.
代碼:
function deleteStackDriverLogs(po) {
var httpRz,options,url;
/*
po.id = GCP project ID - https://console.cloud.google.com/home/dashboard
*/
options = {};
options.method = "delete";
options.muteHttpExceptions = true;
options.headers = {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()};
options.contentType = "application/json";
url = 'https://logging.googleapis.com/v2/';
options.payload = JSON.stringify({
logName: 'projects/' + po.id + "/logs/*"
});
httpRz = UrlFetchApp.fetch(url,options);
Logger.log('response code: ' + httpRz.getResponseCode());
//Logger.log('httpRz.getAllHeaders(): ' + JSON.stringify(httpRz.getAllHeaders()))
//Logger.log(httpRz.getContentText())
}
function testDlet() {
deleteStackDriverLogs({"id":"project-id-your-GCP-id-here"});
}
文檔: https://cloud.google.com/logging/docs/reference/v2/rest/v2/logs/delete
如果只使用沒有有效負載的 URL,那么我會得到沒有解釋的響應代碼 404。
我嘗試了 url 的許多變體。
url = 'https://logging.googleapis.com/v2/logName={projects/' + po.id + '}';//404
url = 'https://logging.googleapis.com/v2/logName=projects/' + po.id + '/';//404
url = 'https://logging.googleapis.com/v2/logName=projects/' + po.id;//404
url = 'https://logging.googleapis.com/v2/logName=projects/' + po.id + '/logs/*/';//400
url = 'https://logging.googleapis.com/v2/logName=projects/' + po.id + '/logs/';//404
文檔聲明日志 ID 必須是 URL 編碼的。 但是,我不確定日志 ID 使用什么。
我相信你的目標如下。
為此,這個答案怎么樣?
logName
。logName
作為端點的路徑。當以上幾點反映到您的腳本時,它變成如下。
function deleteStackDriverLogs(po) {
// --- I added below script.
const endpoint = `https://logging.googleapis.com/v2/projects/${po.id}/logs`;
const res = UrlFetchApp.fetch(endpoint, {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}});
const obj = JSON.parse(res.getContentText());
const logName = obj.logNames.filter(e => e.includes("console_logs"))[0];
/// ---
var httpRz,options,url;
/*
po.id = GCP project ID - https://console.cloud.google.com/home/dashboard
*/
options = {};
options.method = "delete";
options.muteHttpExceptions = true;
options.headers = {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()};
url = 'https://logging.googleapis.com/v2/' + logName; // Modified
httpRz = UrlFetchApp.fetch(url,options);
Logger.log('response code: ' + httpRz.getResponseCode());
//Logger.log('httpRz.getAllHeaders(): ' + JSON.stringify(httpRz.getAllHeaders()))
//Logger.log(httpRz.getContentText())
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.