Günlüğe kaydetme, kodun hatalarını ayıklamak ve izlemek için önemli bir araçtır. Cloud Functions size Node.js veya Python için günlükçü SDK'sını veya web için geliştirme yapmak için console
nesne standardını kullanma seçeneğini sunar.
Cloud Logging ücretli bir hizmettir; Ücretsiz kotayı aşarsanız faturalandırılabilirsiniz. Daha fazla bilgi için Cloud Logging fiyatlandırmasına bakın.
Günlük yazma
Cloud Functions günlükçü SDK'sını kullanma
Cloud Functions logger SDK'sı, işlevlerden Cloud Logging'e durumu raporlamak için standart bir arayüz sağlar. Bu SDK'yı, olayları yapılandırılmış verilerle günlüğe kaydetmek için kullanabilirsiniz; böylece analiz ve izleme daha kolay hale gelir.
logger
alt paketinden içe aktarın:
Node.js
// All available logging functions
const {
log,
info,
debug,
warn,
error,
write,
} = require("firebase-functions/logger");
Piton
from firebase_functions import logger
logger.log()
komutları INFO günlük düzeyine sahiptir.logger.info()
komutları INFO günlük düzeyine sahiptir.logger.warn()
komutları WARNING günlük düzeyine sahiptir.logger.error()
komutları ERROR günlük düzeyine sahiptir.logger.debug()
komutları DEBUG günlük düzeyine sahiptir.Dahili sistem mesajları DEBUG günlük seviyesine sahiptir.
Bu örnek, temel bir günlük yazan bir işlevi gösterir:
Node.js
exports.helloWorld = onRequest((request, response) => {
// sends a log to Cloud Logging
log("Hello logs!");
response.send("Hello from Firebase!");
});
Piton
@https_fn.on_request()
def hello_world(req: https_fn.Request) -> https_fn.Response:
# sends a log to Cloud Logging
logger.log("Hello logs!")
return https_fn.Response("Hello from Firebase!")
İşlev kodunuzda farklı günlük türleri için farklı günlük düzeyleri kullanın. Yapılandırılmış veriler bir günlüğe son argüman olarak eklenebilir. Bir fonksiyonun her günlük türünü nasıl kullanabileceğine dair bir örnek aşağıda verilmiştir:
Node.js
exports.getInspirationalQuote = onRequest(async (request, response) => {
const db = getFirestore();
const today = new Date();
const quoteOfTheMonthRef = db
.collection("quotes")
.doc(`${today.getFullYear()}`)
.collection("months")
.doc(`${today.getMonth()}`);
const DEFAULT_QUOTE =
"You miss 100% of the shots you don't take. -Wayne Gretzky";
let quote;
try {
const quoteOfTheMonthDocSnap = await quoteOfTheMonthRef.get();
// Attach relevant debugging information with debug()
debug("Monthly quote fetch result", {
docRef: quoteOfTheMonthRef.path,
exists: quoteOfTheMonthDocSnap.exists,
createTime: quoteOfTheMonthDocSnap.createTime,
});
if (quoteOfTheMonthDocSnap.exists) {
quote = quoteOfTheMonthDocSnap.data().text;
} else {
// Use warn() for lower-severity issues than error()
warn("Quote not found for month, sending default instead", {
docRef: quoteOfTheMonthRef.path,
dateRequested: today.toLocaleDateString("en-US"),
});
quote = DEFAULT_QUOTE;
}
} catch (err) {
// Attach an error object as the second argument
error("Unable to read quote from Firestore, sending default instead",
err);
quote = DEFAULT_QUOTE;
}
// Attach relevant structured data to any log
info("Sending a quote!", {quote: quote});
response.json({inspirationalQuote: quote});
});
Piton
@https_fn.on_request()
def get_inspirational_quote(req: https_fn.Request) -> https_fn.Response:
firestore_client = firestore.client()
today = datetime.date.today()
quote_of_the_month_ref = (firestore_client.collection("quotes").doc(str(
today.year)).collection("months").doc(str(today.month)))
default_quote = "Python has been an important part of Google since the beginning, and remains so as the system grows and evolves."
quote = None
try:
quote_of_the_month = quote_of_the_month_ref.get()
# Attach relevant debugging information with debug()
logger.debug(
"Monthly quote fetch result",
docRef=quote_of_the_month.path,
exists=quote_of_the_month.exists,
createTime=quote_of_the_month.createTime,
)
if quote_of_the_month.exists:
quote = quote_of_the_month.to_dict()["text"]
else:
# Use warn() for lower-severity issues than error()
logger.warn(
"Quote not found for month, sending default instead",
doc_reference=quote_of_the_month.path,
date_requested=today.strftime("%Y-%m-%d"),
)
quote = default_quote
except:
e = sys.exc_info()[0]
# Attach an error object as the second argument
logger.error("Unable to read quote from Firestore, sending default instead", error=e)
quote = default_quote
# Attach relevant structured data to any log
logger.info("Sending a quote!", quote=quote)
return https_fn.Response("Hello from Firebase!")
logger.write()
ile, CRITICAL
, ALERT
ve EMERGENCY
ek günlük önem düzeylerine sahip günlük girişleri yazabilirsiniz. Bkz. LogSeverity .
Node.js
exports.appHasARegression = onRegressionAlertPublished((event) => {
write({
// write() lets you set additional severity levels
// beyond the built-in logger functions
severity: "EMERGENCY",
message: "Regression in production app",
issue: event.data.payload.issue,
lastOccurred: event.data.payload.resolveTime,
});
});
Piton
@crashlytics_fn.on_regression_alert_published()
def app_has_regression(alert: crashlytics_fn.CrashlyticsRegressionAlertEvent) -> None:
logger.write(
severity="EMERGENCY",
message="Regression in production app",
issue=alert.data.payload.issue,
last_occurred=alert.data.payload.resolve_time,
)
print(alert)
console.log
kullanma
Bir işlevden oturum açmak için önerilen çözüm, platformunuz için günlükçü SDK'sını kullanmaktır. Node.js ile bunun yerine console.log
ve console.error
gibi standart JavaScript günlük kaydı çağrılarını kullanabilirsiniz, ancak öncelikle standart yöntemlerin düzgün çalışması için yama uygulamak üzere özel bir modüle ihtiyacınız vardır:
require("firebase-functions/logger/compat");
Kaydedici uyumluluk modülüne ihtiyaç duyduktan sonra, kodunuzda console.log()
yöntemlerini normal şekilde kullanabilirsiniz:
exports.helloError = functions.https.onRequest((request, response) => {
console.log('I am a log entry!');
response.send('Hello World...');
});
-
console.log()
komutları INFO günlük düzeyine sahiptir. -
console.info()
komutları INFO günlük düzeyine sahiptir. -
console.warn()
komutları ERROR günlük düzeyine sahiptir. -
console.error()
komutları ERROR günlük düzeyine sahiptir. - Dahili sistem mesajları DEBUG günlük seviyesine sahiptir.
Günlükleri görüntüleme
Bulut İşlevlerine ilişkin günlükler, Google Cloud konsolunda , Cloud Logging kullanıcı arayüzünde veya firebase
komut satırı aracı aracılığıyla görüntülenebilir.
Firebase CLI'yi kullanma
Günlükleri firebase
aracıyla görüntülemek için functions:log
komutunu kullanın:
firebase functions:log
Belirli bir işlevin günlüklerini görüntülemek için işlev adını bağımsız değişken olarak sağlayın:
firebase functions:log --only <FUNCTION_NAME>
Günlük görüntüleme seçeneklerinin tamamı için, functions:log
yardımını görüntüleyin:
firebase help functions:log
Google Cloud konsolunu kullanma
İşlevlere ilişkin günlükleri Google Cloud konsolunda görüntüleyebilirsiniz.
Cloud Logging kullanıcı arayüzünü kullanma
Cloud Functions'a ilişkin günlükleri Cloud Logging kullanıcı arayüzünde görüntüleyebilirsiniz .
Günlükleri analiz etme
Cloud Logging, Cloud Functions'ınızı izlemek için kullanabileceğiniz güçlü bir günlük analiz araçları paketi sunar.
Grafikler ve uyarılar
İşlevlerinizi izlemek için günlük tabanlı ölçümler oluşturduktan sonra, bu ölçümlere dayalı grafikler ve uyarılar oluşturabilirsiniz. Örneğin, zaman içindeki gecikmeyi görselleştirmek için bir grafik oluşturabilir veya belirli bir hatanın çok sık meydana gelmesi durumunda sizi bilgilendirecek bir uyarı oluşturabilirsiniz.