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




commit 99779e3c2e4e7cadaf8a7071a3f48aebda8da9bf
Author: Evan Welsh <contact evanwelsh com>
Date:   Sun Jul 4 22:45:49 2021 -0700

    glib: Implement override for structured logging hook

 .eslintrc.yml                     |  1 +
 installed-tests/js/meson.build    |  1 +
 installed-tests/js/testConsole.js | 55 +++++++++++++++++++++++++++++++
 libgjs-private/gjs-util.c         | 69 +++++++++++++++++++++++++++++++++++++++
 libgjs-private/gjs-util.h         | 17 ++++++++++
 modules/core/overrides/GLib.js    | 27 +++++++++++++++
 6 files changed, 170 insertions(+)
---
diff --git a/.eslintrc.yml b/.eslintrc.yml
index 7ddf0e38..80998ba0 100644
--- a/.eslintrc.yml
+++ b/.eslintrc.yml
@@ -243,6 +243,7 @@ rules:
   yield-star-spacing: error
   yoda: error
 globals:
+  console: readonly
   ARGV: readonly
   Debugger: readonly
   GIRepositoryGType: readonly
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..2739237e
--- /dev/null
+++ b/installed-tests/js/testConsole.js
@@ -0,0 +1,55 @@
+// 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();
+    });
+
+    afterAll(function () {
+        GLib.log_set_writer_default();
+    });
+
+    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..e7fbc1a7 100644
--- a/libgjs-private/gjs-util.c
+++ b/libgjs-private/gjs-util.c
@@ -213,3 +213,72 @@ 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;
+
+GLogWriterOutput gjs_log_writer_func_wrapper(GLogLevelFlags log_level,
+                                             const GLogField* fields,
+                                             gsize n_fields,
+                                             gpointer user_data) {
+    WriterFuncData* data = (struct WriterFuncData*)user_data;
+    GjsGLogWriterFunc func = data->func;
+
+    GVariant** children = g_malloc0(n_fields * sizeof(GVariant*));
+    size_t f;
+    for (f = 0; f < n_fields; f++) {
+        const GLogField* field = &fields[f];
+
+        GVariant* key = g_variant_new_string(field->key);
+        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);
+        }
+
+        children[f] = g_variant_new_dict_entry(key, value);
+    }
+
+    GVariant* string_fields = g_variant_new_array(
+        g_variant_type_new_dict_entry(
+            G_VARIANT_TYPE_STRING,
+            g_variant_type_new_maybe(G_VARIANT_TYPE_STRING)),
+        children, n_fields);
+    GLogWriterOutput output =
+        func(log_level, string_fields, data->wrapped_user_data);
+
+    return output;
+}
+
+void gjs_log_set_writer_default() {
+    g_log_set_writer_func(g_log_writer_default, NULL, NULL);
+}
+static void gjs_log_user_data_free(void* user_data) {
+    WriterFuncData* data = (struct WriterFuncData*)user_data;
+    data->wrapped_user_data_free(data->wrapped_user_data);
+    g_free(data);
+}
+
+/**
+ * gjs_log_set_writer_func
+ * @func: (scope call): callback with log data
+ * @user_data: (closure): user data for @func
+ * @user_data_free: destroy for @user_data
+ */
+void gjs_log_set_writer_func(GjsGLogWriterFunc func, void* user_data,
+                             GDestroyNotify user_data_free) {
+    WriterFuncData* data =
+        (struct WriterFuncData*)g_malloc0(sizeof(WriterFuncData));
+    data->func = func;
+    data->wrapped_user_data = user_data;
+    data->wrapped_user_data_free = user_data_free;
+
+    g_log_set_writer_func(gjs_log_writer_func_wrapper, data,
+                          gjs_log_user_data_free);
+}
diff --git a/libgjs-private/gjs-util.h b/libgjs-private/gjs-util.h
index 320337c5..dc3ea340 100644
--- a/libgjs-private/gjs-util.h
+++ b/libgjs-private/gjs-util.h
@@ -48,6 +48,23 @@ 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,
+                                              gpointer 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();
+
 /* For imports.gettext */
 typedef enum
 {
diff --git a/modules/core/overrides/GLib.js b/modules/core/overrides/GLib.js
index 5e3800a9..7bd02857 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.deepUnpack()};
+                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]