Siddhartha Das
Siddhartha Das

Reputation: 251

Include timestamp in vala log message

I have a lot of debug(...) and info(...) logging in my vala application code and I'm trying to add timestamps in the logging.

I am avoiding the set_writer_func as it requires glib "2.50" and eOS Loki is at glib 2.48. The MVCE below kind of gives me the right output format but I cannot set the log level i.e. setting the level as INFO should not output the DEBUG messages.

Thanks in advance for any help / pointers on this.

public class LogTest {
    public static int main(string[] args) {
        Environment.set_variable ("G_MESSAGES_DEBUG", "all", true);
        Log.set_default_handler(
            (domain, level, message) => {
                domain = "My.Domain";
                level = GLib.LogLevelFlags.LEVEL_INFO;
                print("[%s] [%s] %s\n", Time.local(time_t()).to_string(), level.to_string(), message);
            }
        );

        debug("logging debug");
        info("logging info");
        warning("logging warning");

        return 0;
    }
}

This gives the following output, I was not expecting debug to show up.

[2018-02-16 23:14:53] [G_LOG_LEVEL_INFO] logging.vala:12: logging debug
[2018-02-16 23:14:53] [G_LOG_LEVEL_INFO] logging.vala:13: logging info
[2018-02-16 23:14:53] [G_LOG_LEVEL_INFO] logging.vala:14: logging warning

Granite.Services.Logger seems to be having what I want, so will go with it for the moment. Adding the MVCE here just in case it benefits someone.

using Granite.Services;
public class LogTest {
    public static int main(string[] args) {
        Environment.set_variable ("G_MESSAGES_DEBUG", "all", true);

        Logger.initialize("My.Domain");
        Logger.DisplayLevel = LogLevel.INFO;

        debug("logging debug");
        info("logging info");
        warning("logging warning");
        return 0;
    }
}

Compile with valac --pkg=granite logging.vala and then run:

[INFO 12:44:33.454785] logging.vala:26: logging info
[WARNING 12:44:33.454839] logging.vala:27: logging warning

Upvotes: 2

Views: 323

Answers (1)

nemequ
nemequ

Reputation: 17492

The code to handle filtering based on G_MESSAGES_DEBUG is part of the default log handler; if you implement a custom handler it's up to you to also filter messages based on whatever settings you want.

Upvotes: 1

Related Questions