[gjs/ewlsh/glogfield-support] glib: Implement override for structured logging hook




commit 6e3a3d3986e362b2a739193f363b57b248c517c6
Author: Evan Welsh <contact evanwelsh com>
Date:   Sat Jul 10 23:33:22 2021 -0700

    glib: Implement override for structured logging hook

 installed-tests/js/meson.build    |  1 +
 installed-tests/js/testConsole.js | 51 ++++++++++++++++++++++
 libgjs-private/gjs-util.c         | 91 +++++++++++++++++++++++++++++++++++++++
 libgjs-private/gjs-util.h         | 20 +++++++++
 modules/core/overrides/GLib.js    | 27 ++++++++++++
 5 files changed, 190 insertions(+)
---
diff --git a/installed-tests/js/meson.build b/installed-tests/js/meson.build
index e11f1418..615fc967 100644
--- a/installed-tests/js/meson.build
+++ b/installed-tests/js/meson.build
@@ -94,6 +94,7 @@ subdir('libgjstesttools')
 jasmine_tests = [
     'self',
     'ByteArray',
+    'Console',
     'Exceptions',
     'Format',
     'Fundamental',
diff --git a/installed-tests/js/testConsole.js b/installed-tests/js/testConsole.js
new file mode 100644
index 00000000..6a9577a4
--- /dev/null
+++ b/installed-tests/js/testConsole.js
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
+// SPDX-FileCopyrightText: 2021 Evan Welsh <contact evanwelsh com>
+
+// eslint-disable-next-line
+/// <reference types="jasmine" />
+
+const {GLib} = imports.gi;
+
+describe('Structured logging handler', function () {
+    /** @type {jasmine.Spy<(_level: any, _fields: any) => any>} */
+    let writer_func;
+
+    beforeAll(function () {
+        writer_func = jasmine.createSpy(
+            'Log test writer func',
+            function (_level, _fields) {
+                return GLib.LogWriterOutput.HANDLED;
+            }
+        );
+
+        writer_func.and.callThrough();
+
+        GLib.log_set_writer_func(writer_func);
+    });
+
+    beforeEach(function () {
+        writer_func.calls.reset();
+    });
+
+    it('writes a message', function () {
+        GLib.log_structured('Gjs-Console', GLib.LogLevelFlags.LEVEL_MESSAGE, {
+            MESSAGE: 'a message',
+        });
+
+        expect(writer_func).toHaveBeenCalledWith(
+            GLib.LogLevelFlags.LEVEL_MESSAGE,
+            jasmine.objectContaining({MESSAGE: 'a message'})
+        );
+    });
+
+    it('writes a warning', function () {
+        GLib.log_structured('Gjs-Console', GLib.LogLevelFlags.LEVEL_WARNING, {
+            MESSAGE: 'a warning',
+        });
+
+        expect(writer_func).toHaveBeenCalledWith(
+            GLib.LogLevelFlags.LEVEL_WARNING,
+            jasmine.objectContaining({MESSAGE: 'a warning'})
+        );
+    });
+});
diff --git a/libgjs-private/gjs-util.c b/libgjs-private/gjs-util.c
index 15060950..2f474249 100644
--- a/libgjs-private/gjs-util.c
+++ b/libgjs-private/gjs-util.c
@@ -213,3 +213,94 @@ void gjs_list_store_sort(GListStore *store, GjsCompareDataFunc compare_func,
                          void *user_data) {
   g_list_store_sort(store, (GCompareDataFunc)compare_func, user_data);
 }
+
+typedef struct WriterFuncData {
+    GjsGLogWriterFunc func;
+    void* wrapped_user_data;
+    GDestroyNotify wrapped_user_data_free;
+} WriterFuncData;
+
+static gboolean log_writer_set_from_gjs = FALSE;
+static void* log_writer_user_data = NULL;
+static GDestroyNotify log_writer_user_data_free = NULL;
+
+GLogWriterOutput gjs_log_writer_func_wrapper(GLogLevelFlags log_level,
+                                             const GLogField* fields,
+                                             gsize n_fields,
+                                             gpointer user_data) {
+    GjsGLogWriterFunc func = (GjsGLogWriterFunc)user_data;
+    GVariantDict* dict = g_variant_dict_new(NULL);
+    size_t f;
+    for (f = 0; f < n_fields; f++) {
+        const GLogField* field = &fields[f];
+
+        GVariant* value;
+        if (field->length == -1) {
+            value = g_variant_new_maybe(G_VARIANT_TYPE_STRING,
+                                        g_variant_new_string(field->value));
+        } else {
+            value = g_variant_new_maybe(G_VARIANT_TYPE_STRING, NULL);
+        }
+
+        g_variant_dict_insert_value(dict, field->key, value);
+    }
+
+    GVariant* string_fields = g_variant_dict_end(dict);
+    g_variant_ref(string_fields);
+    g_variant_dict_unref(dict);
+
+    GLogWriterOutput output =
+        func(log_level, string_fields, log_writer_user_data);
+
+    g_variant_unref(string_fields);
+    return output;
+}
+
+/**
+ * gjs_log_set_writer_default
+ *
+ * Sets the structured logging writer function back to the platform default.
+ */
+void gjs_log_set_writer_default() {
+    if (log_writer_user_data_free) {
+        log_writer_user_data_free(log_writer_user_data);
+    }
+
+    g_log_set_writer_func(g_log_writer_default, NULL, NULL);
+    log_writer_set_from_gjs = FALSE;
+    log_writer_user_data_free = NULL;
+    log_writer_user_data = NULL;
+}
+
+/**
+ * gjs_log_set_writer_default
+ *
+ * Resets the structured logging writer function back to the platform default
+ * only if it was previously set from GJS. This function has no impact if
+ * the logging writer function was set directly using g_log_set_writer_func.
+ */
+void gjs_log_reset_writer() {
+    if (!log_writer_set_from_gjs)
+        return;
+
+    gjs_log_set_writer_default();
+}
+
+/**
+ * gjs_log_set_writer_func
+ * @func: (scope notified): callback with log data
+ * @user_data: (closure): user data for @func
+ * @user_data_free: (destroy user_data_free): destroy for @user_data
+ *
+ * Sets a given function as the writer function for structured logging,
+ * passing log fields as a variant. If called from JavaScript the application
+ * must call gjs_log_set_writer_default prior to exiting.
+ */
+void gjs_log_set_writer_func(GjsGLogWriterFunc func, void* user_data,
+                             GDestroyNotify user_data_free) {
+    log_writer_user_data = user_data;
+    log_writer_user_data_free = user_data_free;
+    log_writer_set_from_gjs = TRUE;
+
+    g_log_set_writer_func(gjs_log_writer_func_wrapper, func, NULL);
+}
diff --git a/libgjs-private/gjs-util.h b/libgjs-private/gjs-util.h
index 320337c5..8c00ce8a 100644
--- a/libgjs-private/gjs-util.h
+++ b/libgjs-private/gjs-util.h
@@ -48,6 +48,26 @@ GJS_EXPORT
 void gjs_list_store_sort(GListStore *store, GjsCompareDataFunc compare_func,
                          void *user_data);
 
+/**
+ * GjsGLogWriterFunc:
+ * @level: the log level
+ * @fields: a dictionary variant with type a{sms}
+ * @user_data: user data
+ */
+typedef GLogWriterOutput (*GjsGLogWriterFunc)(GLogLevelFlags level,
+                                              const GVariant* fields,
+                                              void* user_data);
+
+GJS_EXPORT
+void gjs_log_set_writer_func(GjsGLogWriterFunc func, gpointer user_data,
+                             GDestroyNotify user_data_free);
+
+GJS_EXPORT
+void gjs_log_set_writer_default();
+
+GJS_EXPORT
+void gjs_log_reset_writer();
+
 /* For imports.gettext */
 typedef enum
 {
diff --git a/modules/core/overrides/GLib.js b/modules/core/overrides/GLib.js
index 5e3800a9..9a28c1de 100644
--- a/modules/core/overrides/GLib.js
+++ b/modules/core/overrides/GLib.js
@@ -319,6 +319,33 @@ function _init() {
         GLib.log_variant(logDomain, logLevel, new GLib.Variant('a{sv}', fields));
     };
 
+    // GjsPrivate depends on GLib so we cannot import it
+    // before GLib is fully resolved.
+
+    this.log_set_writer_func_variant = function (...args) {
+        const {log_set_writer_func} = imports.gi.GjsPrivate;
+
+        log_set_writer_func(...args);
+    };
+
+    this.log_set_writer_default = function (...args) {
+        const {log_set_writer_default} = imports.gi.GjsPrivate;
+
+        log_set_writer_default(...args);
+    };
+
+    this.log_set_writer_func = function (writer_func) {
+        const {log_set_writer_func} = imports.gi.GjsPrivate;
+        if (typeof writer_func !== 'function') {
+            log_set_writer_func(writer_func);
+        } else {
+            log_set_writer_func(function (logLevel, stringFields) {
+                const stringFieldsObj = {...stringFields.recursiveUnpack()};
+                return writer_func(logLevel, stringFieldsObj);
+            });
+        }
+    };
+
     this.VariantDict.prototype.lookup = function (key, variantType = null, deep = false) {
         if (typeof variantType === 'string')
             variantType = new GLib.VariantType(variantType);


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]