[polari] logging: Replace custom functions with new console module



commit 0781254b1a53182fdb7bcd7c5e9743cb683ac72f
Author: Florian Müllner <fmuellner gnome org>
Date:   Thu Aug 12 16:22:23 2021 +0200

    logging: Replace custom functions with new console module
    
    gjs' console implementation uses glib's structured logging underneath,
    which was the motivation for creating custom log functions. The only
    thing that's currently missing from the console module is including
    the `CODE_FILE`, `CODE_FUNC` and `CODE_LINE` standard fields with
    log messages, but that's not enough reason for keeping our own
    logging.
    
    https://gitlab.gnome.org/GNOME/polari/-/merge_requests/214

 lint/eslintrc-gjs.yml  |  1 +
 meson.build            |  2 +-
 src/application.js     | 35 +++++++++++++++++++++++++----------
 src/entryArea.js       |  3 ++-
 src/ircParser.js       |  4 ++--
 src/logging.js         | 36 ------------------------------------
 src/main.js            |  3 ---
 src/meson.build        |  1 -
 src/networksManager.js |  6 ++++--
 src/telepathyClient.js | 32 ++++++++++++++++++++++----------
 src/thumbnailer.js     | 12 ++++++++++--
 src/urlPreview.js      |  8 +++++---
 src/utils.js           | 15 ++++++++++-----
 13 files changed, 82 insertions(+), 76 deletions(-)
---
diff --git a/lint/eslintrc-gjs.yml b/lint/eslintrc-gjs.yml
index dadf40bd..26bd8c74 100644
--- a/lint/eslintrc-gjs.yml
+++ b/lint/eslintrc-gjs.yml
@@ -259,5 +259,6 @@ globals:
   window: readonly
   TextEncoder: readonly
   TextDecoder: readonly
+  console: readonly
 parserOptions:
   ecmaVersion: 2020
diff --git a/meson.build b/meson.build
index 692d5399..c886c4a9 100644
--- a/meson.build
+++ b/meson.build
@@ -37,7 +37,7 @@ gio = dependency('gio-2.0', version: '>= 2.43.4')
 gtk3 = dependency('gtk+-3.0', version: '>= 3.21.6')
 telepathy_glib = dependency('telepathy-glib')
 girepository = dependency('gobject-introspection-1.0')
-gjs = dependency('gjs-1.0', version: '>= 1.67.2')
+gjs = dependency('gjs-1.0', version: '>= 1.69.2')
 
 conf = configuration_data()
 
diff --git a/src/application.js b/src/application.js
index a1d35019..6b56b664 100644
--- a/src/application.js
+++ b/src/application.js
@@ -6,6 +6,8 @@ import Gtk from 'gi://Gtk?version=3.0';
 import Polari from 'gi://Polari';
 import Tp from 'gi://TelepathyGLib';
 
+import { setConsoleLogDomain } from 'console';
+
 import AccountsMonitor from './accountsMonitor.js';
 import * as AppNotifications from './appNotifications.js';
 import * as Connections from './connections.js';
@@ -49,6 +51,12 @@ export default GObject.registerClass({
 
         GLib.set_prgname('polari');
         Tp.debug_set_flags(GLib.getenv('TP_DEBUG') || '');
+
+        const logDomain = 'Polari';
+        setConsoleLogDomain(logDomain);
+        if (GLib.log_writer_is_journald(2))
+            GLib.setenv('G_MESSAGES_DEBUG', logDomain, false);
+
         this._retryData = new Map();
         this._nickTrackData = new Map();
         this._demons = [];
@@ -131,12 +139,13 @@ export default GObject.registerClass({
     }
 
     _ensureService(conn, name, opath, iface, command) {
-        debug(`Trying to ensure service ${name}`);
+        console.info(`Trying to ensure service ${name}`);
 
         if (this._checkService(conn, name, opath, iface))
             return;
 
-        log(`Failed to activate service ${name}, starting manually`);
+        console.info(`Failed to activate service ${
+            name}, starting manually`);
 
         let proc = new Gio.Subprocess({ argv: [command] });
 
@@ -144,7 +153,9 @@ export default GObject.registerClass({
             proc.init(null);
             this._demons.push(proc);
         } catch (e) {
-            log(`Failed to launch ${command}: ${e.message}`);
+            console.error(`Failed to launch ${
+                command} to provide service ${name}`);
+            console.debug(e);
         }
     }
 
@@ -155,11 +166,12 @@ export default GObject.registerClass({
 
         let handled = false;
         let id = Gio.bus_watch_name(bus, name, flags, () => {
-            debug('Running as test instance alongside primary instance');
+            console.info(
+                'Running as test instance alongside primary instance');
             this.set_flags(this.flags | Gio.ApplicationFlags.NON_UNIQUE);
             handled = true;
         }, () => {
-            debug('No primary instance found, running normally');
+            console.info('No primary instance found, running normally');
             handled = true;
         });
 
@@ -383,7 +395,8 @@ export default GObject.registerClass({
         try {
             provider.load_from_file(Gio.File.new_for_uri(uri));
         } catch (e) {
-            logError(e, 'Failed to add application style');
+            console.warn('Failed to add application style');
+            console.debug(e);
         }
         Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(),
             provider,
@@ -626,7 +639,8 @@ export default GObject.registerClass({
 
         let params = account.getConnectionParams();
         let { server, account: accountName, port } = params;
-        debug(`Failed to connect to ${server} with username ${accountName}`);
+        console.info(`Failed to connect to ${server} with username ${
+            accountName}`);
 
         let accountServers = [];
         if (account.predefined)
@@ -672,7 +686,7 @@ export default GObject.registerClass({
         let oldParams = account.dup_parameters_vardict().deep_unpack();
         let nick = oldParams['account'].deep_unpack();
 
-        debug(`Retrying with nickname ${nick}_`);
+        console.info(`Retrying with nickname ${nick}_`);
         let params = { account: new GLib.Variant('s', `${nick}_`) };
         this._retryWithParams(account, new GLib.Variant('a{sv}', params));
         return true;
@@ -685,7 +699,7 @@ export default GObject.registerClass({
         if (!server)
             return false;
 
-        debug(`Retrying with ${server.address}:${server.port}`);
+        console.info(`Retrying with ${server.address}:${server.port}`);
         let params = {
             server: new GLib.Variant('s', server.address),
             port: new GLib.Variant('u', server.port),
@@ -718,7 +732,8 @@ export default GObject.registerClass({
             if (reason !== Tp.ConnectionStatusReason.REQUESTED) {
                 let strReason = Object.keys(Tp.ConnectionStatusReason)[reason];
                 let name = account.display_name;
-                debug(`Account ${name} disconnected with reason ${strReason}`);
+                console.info(`Account ${name} disconnected with reason ${
+                    strReason}`);
 
                 // Connection failed, keep tp from retrying over and over
                 let presence = Tp.ConnectionPresenceType.OFFLINE;
diff --git a/src/entryArea.js b/src/entryArea.js
index 083dca9e..1a2670c8 100644
--- a/src/entryArea.js
+++ b/src/entryArea.js
@@ -432,7 +432,8 @@ export default GObject.registerClass({
             let type = typeof this._pasteContent;
             if (type === 'object')
                 type = this._pasteContent.toString();
-            debug(`Failed to paste content of type ${type}`);
+            console.warn(`Failed to paste content of type ${type}`);
+            console.debug(e);
         } finally {
             this._uploadSpinner.stop();
         }
diff --git a/src/ircParser.js b/src/ircParser.js
index f5f368a5..fa43fd08 100644
--- a/src/ircParser.js
+++ b/src/ircParser.js
@@ -127,7 +127,7 @@ export default class IrcParser {
                 break;
             }
             if (argv.length)
-                log(`Excess arguments to JOIN command: ${argv}`);
+                console.warn(`Excess arguments to JOIN command: ${argv}`);
             if (!ROOM_PREFIXES.some(prefix => room.startsWith(prefix)))
                 room = `#${room}`;
             let { account } = this._room;
@@ -205,7 +205,7 @@ export default class IrcParser {
                 break;
             }
             if (argv.length)
-                log(`Excess arguments to NICK command: ${argv}`);
+                console.warn(`Excess arguments to NICK command: ${argv}`);
 
             this._app.setAccountNick(this._room.account, nick);
             break;
diff --git a/src/main.js b/src/main.js
index 4d59ed4f..7d3be87d 100755
--- a/src/main.js
+++ b/src/main.js
@@ -1,7 +1,6 @@
 import GLib from 'gi://GLib';
 
 import * as Config from './config.js';
-import * as Log from './logging.js';
 import { ngettext } from 'gettext';
 import { programInvocationName, programArgs } from 'system';
 
@@ -35,8 +34,6 @@ pkg.requireSymbol('Gtk', '3.0', 'ScrolledWindow.propagate_natural_width');
 if (!pkg.checkSymbol('Soup', '3.0'))
     pkg.requireSymbol('Soup', '2.4');
 
-Log.init();
-
 import Application from './application.js';
 
 let application = new Application();
diff --git a/src/meson.build b/src/meson.build
index 669eb4b8..275d9eda 100644
--- a/src/meson.build
+++ b/src/meson.build
@@ -15,7 +15,6 @@ js_sources = [
   'initialSetup.js',
   'ircParser.js',
   'joinDialog.js',
-  'logging.js',
   'main.js',
   'mainWindow.js',
   'networksManager.js',
diff --git a/src/networksManager.js b/src/networksManager.js
index 4417b0b1..54a5341d 100644
--- a/src/networksManager.js
+++ b/src/networksManager.js
@@ -21,7 +21,8 @@ export default class NetworksManager {
             [, data] = file.load_contents(null);
             this._parseNetworks(new TextDecoder().decode(data));
         } catch (e) {
-            log(`Failed to load network list: ${e.message}`);
+            console.warn('Failed to load network list');
+            console.debug(e);
         }
     }
 
@@ -30,7 +31,8 @@ export default class NetworksManager {
         try {
             networks = JSON.parse(data);
         } catch (e) {
-            log(`Failed to parse network list: ${e.message}`);
+            console.warn('Failed to parse network list');
+            console.debug(e);
             return false;
         }
 
diff --git a/src/telepathyClient.js b/src/telepathyClient.js
index 31b57805..762fbe88 100644
--- a/src/telepathyClient.js
+++ b/src/telepathyClient.js
@@ -93,7 +93,7 @@ class SASLAuthHandler {
     _onSASLStatusChanged(proxy, sender, [status]) {
         let name = this._channel.connection.get_account().display_name;
         let statusString = Object.keys(SASLStatus)[status];
-        debug(`Auth status for server ${name}: ${statusString}`);
+        console.info(`Auth status for server ${name}: ${statusString}`);
 
         switch (status) {
         case SASLStatus.NOT_STARTED:
@@ -188,7 +188,8 @@ class TelepathyClient extends Tp.BaseClient {
                 null);
             [names] = result.deep_unpack();
         } catch (e) {
-            debug(`Failed to list bus names: ${e}`);
+            console.info('Failed to list bus names');
+            console.debug(e);
         }
 
         this._shellHandlesPrivateChats =
@@ -275,7 +276,7 @@ class TelepathyClient extends Tp.BaseClient {
         let presence = account.reachable
             ? Tp.ConnectionPresenceType.AVAILABLE
             : Tp.ConnectionPresenceType.OFFLINE;
-        debug(`Account ${account.display_name} is now ${account.reachable
+        console.info(`Account ${account.display_name} is now ${account.reachable
             ? 'reachable'
             : 'unreachable'}`);
 
@@ -308,11 +309,13 @@ class TelepathyClient extends Tp.BaseClient {
         let msg = account.requested_status_message;
         let accountName = account.display_name;
 
-        debug(`Setting presence of account "${accountName}" to ${status}`);
+        console.info(`Setting presence of account "${accountName}" to ${status}`);
         try {
             await account.request_presence_async(presence, status, msg);
         } catch (e) {
-            log(`Connection failed: ${e.message}`);
+            console.warn(`Failed to change presence of account "${
+                accountName}" to ${status}`);
+            console.debug(e);
         }
     }
 
@@ -355,7 +358,9 @@ class TelepathyClient extends Tp.BaseClient {
             channel = await req.ensure_and_observe_channel_async(
                 preferredHandler, cancellable);
         } catch (e) {
-            debug(`Failed to ensure channel: ${e.message}`);
+            console.warn(`Failed to ensure channel ${
+                targetId} for account ${account.displayName}`);
+            console.debug(e);
             channelError = Tp.error_get_dbus_name(e.code);
             throw e;
         } finally {
@@ -396,7 +401,9 @@ class TelepathyClient extends Tp.BaseClient {
         try {
             await room.send_identify_message_async(command, username, password);
         } catch (e) {
-            log(`Failed to send identify message: ${e.message}`);
+            console.warn(`Failed to send identify message for ${
+                username} to ${contactName} on ${account.displayName}`);
+            console.debug(e);
         }
         this._connectRooms(account);
     }
@@ -452,8 +459,11 @@ class TelepathyClient extends Tp.BaseClient {
             let tpMessage = Tp.ClientMessage.new_text(type, message);
             await channel.send_message_async(tpMessage, 0);
         } catch (e) {
-            if (message)
-                log(`Failed to send message: ${e.message}`);
+            if (!message)
+                return; // already logged by _requestChannel()
+            console.warn(`Failed to send message to ${channelName} on ${
+                account.displayName}`);
+            console.debug(e);
         }
     }
 
@@ -483,7 +493,9 @@ class TelepathyClient extends Tp.BaseClient {
         try {
             await room.channel.leave_async(reason, message);
         } catch (e) {
-            log(`Failed to leave channel: ${e.message}`);
+            console.warn(`Failed to leave channel ${
+                room.channelName} on ${room.account.displayName}`);
+            console.debug(e);
         }
     }
 
diff --git a/src/thumbnailer.js b/src/thumbnailer.js
index 4b3dabf8..ed6350ea 100644
--- a/src/thumbnailer.js
+++ b/src/thumbnailer.js
@@ -5,6 +5,7 @@ import GLib from 'gi://GLib';
 import GObject from 'gi://GObject';
 import Gtk from 'gi://Gtk?version=3.0';
 
+import { setConsoleLogDomain } from 'console';
 import { programArgs } from 'system';
 
 import gi from 'gi';
@@ -94,7 +95,8 @@ let PreviewWindow = GObject.registerClass({
             clip = await getClipOp;
             snapshot = await snapshotOp;
         } catch (e) {
-            log(`Creating snapshot failed: ${e}`);
+            console.warn(`Failed to create snapshot of ${this.uri}`);
+            console.debug(e);
             this.emit('snapshot-failed');
             return;
         }
@@ -121,7 +123,8 @@ let PreviewWindow = GObject.registerClass({
             let res = await this._view.run_javascript(script, null);
             obj = res.get_js_value();
         } catch (e) {
-            log(`Failed to get clip information: ${e} (${e.code})`);
+            console.warn(`Failed to get clip information from ${this.uri}`);
+            console.debug(e);
         }
 
         if (!obj || obj.is_null())
@@ -163,6 +166,11 @@ class App {
     run() {
         Gtk.init(null);
 
+        const logDomain = 'Polari Thumbnailer';
+        setConsoleLogDomain(logDomain);
+        if (GLib.log_writer_is_journald(2))
+            GLib.setenv('G_MESSAGES_DEBUG', logDomain, false);
+
         let window = new PreviewWindow({
             uri: this._uri,
             default_width: 10 * PREVIEW_WIDTH,
diff --git a/src/urlPreview.js b/src/urlPreview.js
index 1f8e37d6..80bd36b4 100644
--- a/src/urlPreview.js
+++ b/src/urlPreview.js
@@ -161,10 +161,12 @@ export default GObject.registerClass({
             const filename = await thumbnailer.getThumbnail(this.uri);
             this._image.set_from_file(filename);
         } catch (e) {
-            if (e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.NETWORK_UNREACHABLE))
+            if (e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.NETWORK_UNREACHABLE)) {
                 this._imageLoaded = false;
-            else
-                log(`Thumbnail generation for ${this.uri} failed: ${e}`);
+            } else {
+                console.info(`Failed to generate thumbnail for ${this.uri}`);
+                console.debug(e);
+            }
             this._image.set({
                 icon_name: 'image-x-generic-symbolic',
                 pixel_size: 64,
diff --git a/src/utils.js b/src/utils.js
index b38f87d8..76f2e13a 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -166,7 +166,9 @@ export function needsOnetimeAction(name) {
     } catch (e) {
         if (e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.EXISTS))
             return false;
-        log(`Failed to mark onetime action ${name} as completed: ${e.message}`);
+        console.warn(`Failed to mark onetime action ${
+            name} as completed`);
+        console.debug(e);
     }
     return true;
 }
@@ -198,7 +200,8 @@ async function _storePassword(schema, label, account, password) {
         await Secret.password_store(schema, attr, coll, label, password, null);
     } catch (e) {
         const name = account.display_name;
-        log(`Failed to store password for account ${name}: ${e.message}`);
+        console.warn(`Failed to store password for account ${name}`);
+        console.debug(e);
         throw e;
     }
 }
@@ -228,7 +231,8 @@ async function _lookupPassword(schema, account) {
         password = await Secret.password_lookup(schema, attr, null);
     } catch (e) {
         const name = account.display_name;
-        log(`Failed to lookup password for account "${name}": ${e.message}`);
+        console.warn(`Failed to lookup password for account ${name}`);
+        console.debug(e);
         throw e;
     }
 
@@ -257,7 +261,8 @@ async function _clearPassword(schema, account) {
         await Secret.password_clear(schema, attr, null);
     } catch (e) {
         const name = account.display_name;
-        log(`Failed to clear password for account "${name}": ${e.message}`);
+        console.warn(`Failed to clear password for account ${name}`);
+        console.debug(e);
         throw e;
     }
 }
@@ -310,7 +315,7 @@ export function openURL(url) {
     } catch (e) {
         let n = new AppNotifications.SimpleOutput(_('Failed to open link'));
         app.notificationQueue.addNotification(n);
-        debug(`Failed to open ${url}: ${e.message}`);
+        console.debug(`Failed to open ${url}: %o`, e);
     }
 }
 


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