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




commit 2acd73179fdbb6378740fd8925c9ac6deab706bb
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 | 51 ++++++++++++++++++++++++++++
 libgjs-private/gjs-util.c         | 70 +++++++++++++++++++++++++++++++++++++++
 libgjs-private/gjs-util.h         | 17 ++++++++++
 modules/core/overrides/GLib.js    | 16 +++++++++
 6 files changed, 156 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..f027cb1e
--- /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('Console log levels', 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('logs a message', function () {
+        console.log('a message');
+
+        expect(writer_func).toHaveBeenCalledWith(
+            GLib.LogLevelFlags.LEVEL_MESSAGE,
+            jasmine.objectContaining({MESSAGE: 'a message'})
+        );
+    });
+
+    it('logs a warning', function () {
+        console.warn('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..e4092cf1 100644
--- a/libgjs-private/gjs-util.c
+++ b/libgjs-private/gjs-util.c
@@ -213,3 +213,73 @@ 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("s", g_variant_new_string(field->value));
+        } else {
+            value = g_variant_new_maybe("s", 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_new(G_VARIANT_TYPE_STRING),
+                                g_variant_type_new_maybe(
+                                    g_variant_type_new(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..359a4356 100644
--- a/modules/core/overrides/GLib.js
+++ b/modules/core/overrides/GLib.js
@@ -319,6 +319,22 @@ function _init() {
         GLib.log_variant(logDomain, logLevel, new GLib.Variant('a{sv}', fields));
     };
 
+    const {log_set_writer_func, log_set_writer_default} = imports.gi.GjsPrivate;
+
+    this.log_set_writer_func_variant = log_set_writer_func;
+    this.log_set_writer_default = log_set_writer_default;
+
+    this.log_set_writer_func = function (writer_func) {
+        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]