firebase 如何查看Cloud Firestore日志?

6ojccjat  于 2023-06-07  发布在  其他
关注(0)|答案(3)|浏览(497)

我希望看到Cloud Firestores日志,就像我可以看到Cloud Functions for Firebase一样。在Firebase控制台的Functions选项卡中有一个logs选项卡。同样,我希望看到Cloud Firestore。怎么做?

cgfeq70w

cgfeq70w1#

我写了一个firebase云函数来记录所有活动到Firestore:

/**
 * Logs all database activity
 *
 * @type {CloudFunction<Change<DocumentSnapshot>>}
 */
exports.dbLogger = functions.firestore
  .document('{collection}/{id}')
  .onWrite(async (change, context) => {
    const {collection, id} = context.params;
    if (collection !== 'firestore_log') {
      const event = context.eventType;
      const data = change.after.data();
      const created_at = Date.now();
      admin.firestore().collection('firestore_log').add({collection, id, event, data, created_at});
    }
  });

以下是记录的数据示例:

请注意,这是一个快速开发版本,只记录一切;在生产中,我们有Firestore规则来拒绝对表的任何读/写(firebase函数上的管理员仍然可以访问它们):

// firestore.rules
match /firestore_log/{entryId} {
    allow read: if false;
    allow write: if false;
}

并过滤记录的集合以避免持久化敏感数据。
请注意,如果您更喜欢将其持久化在日志中而不是Firestore中,则可以使用console.log({....})。我更喜欢Firestore,因为它的设计是为了处理更大的数据集。

8xiog9wr

8xiog9wr2#

目前没有Cloud Firestore的日志条目向开发人员公开,因此目前我们建议单独记录您的任何统计信息。

laximzn5

laximzn53#

ForrestLymans代码:

exports.dbLog = functions.firestore
  .document('LICENCE/{licenceId}/{collection}/{docId}')
  .onWrite(async (change, context) => {
    try {
      const { collection, docId, licenceId } = context.params;
      const event = context.eventType;
      const created_at = admin.firestore.FieldValue.serverTimestamp();

      const licenceRef = admin.firestore().collection('LICENCE').doc(licenceId);

      // Get the current year and month
      const now = admin.firestore.Timestamp.now();
      const year = now.toDate().getFullYear();
      const month = now.toDate().getMonth() + 1; // Months are zero-based, so we add 1

      // Create the subcollection references for write and delete logs based on the year and month
      const logWriteCollectionRef = licenceRef.collection(`LOGS/writes/${year}_${month}`);
      const logDeleteCollectionRef = licenceRef.collection(`LOGS/deletes/${year}_${month}`);

      if (collection !== 'firestore_write_log' && collection !== 'firestore_delete_log') {
        if (event === 'write' && change.after.exists) {
          const data = change.after.data();

          const logRef = logWriteCollectionRef.doc();
          await logRef.set({ collection, docId, event, data, created_at });
        } else if (event === 'delete') {
          const snapshot = await admin.firestore()
            .collection(collection)
            .doc(docId)
            .get();
          if (snapshot.exists) {
            const data = snapshot.data();

            const logRef = logDeleteCollectionRef.doc();
            await logRef.set({ collection, docId, event, data, created_at });
          }
        }
      }
    } catch (error) {
      console.error('Error logging Firestore activity:', error);
    }
  });

这将按用户/顶层拆分日志

相关问题