使用ASL登录console.app

在OSX 10.8中输出到stdout和stderr不再以Console.app结尾.我想在不使用NSLog的情况下在Console.app中获取输出,因为我需要支持使用基本打印语句来打印调试信息的代码(有关一些背景信息,请参阅 https://bitbucket.org/ronaldoussoren/py2app/issue/77).

NSLog输出以“某种方式”在ASL(Apple系统日志)日志中结束,因为您可以使用“syslog -C”查看这些日志.这就是我尝试将此代码添加到我的应用程序的原因:

aslclient c = asl_open("py2app", "com.apple.console", ASL_OPT_NO_DELAY);
int fd = dup(2);
asl_set_filter(c, ASL_FILTER_MASK_UPTO(ASL_LEVEL_DEBUG));
asl_add_log_file(c, fd);
asl_log(c, NULL, ASL_LEVEL_INFO, "Hello world from py2app launcher");
asl_log_descriptor(c, NULL, ASL_LEVEL_INFO, 1, ASL_LOG_DESCRIPTOR_WRITE);
asl_log_descriptor(c, NULL, ASL_LEVEL_INFO, 2, ASL_LOG_DESCRIPTOR_WRITE);

这有点工作:当我向stdout流写行时,这些行由ASL转换:输出现在以通常的日志记录前缀作为前缀:

Nov 20 13:46:14 Gondolin.local py2app[43722] <Info>: Hello world from py2app launcher

但是,日志文件不会在ASL数据存储区或Console.app中结束.

有谁知道我做错了什么?

以下C代码似乎做我想要的:

#include <asl.h>
#include <unistd.h>
#include <stdio.h>

static void
setup_logging(void)
{
        aslmsg msg;
        aslclient c = asl_open("py2app", "com.apple.console", 0);

        msg = asl_new(ASL_TYPE_MSG);
        asl_set(msg, ASL_KEY_FACILITY, "com.apple.console");
        asl_set(msg, ASL_KEY_LEVEL, ASL_STRING_NOTICE);
        asl_set(msg, ASL_KEY_READ_UID, "-1");

        int fd = dup(2);
        //asl_set_filter(c, ASL_FILTER_MASK_UPTO(ASL_LEVEL_DEBUG));
        asl_add_log_file(c, fd);
        asl_log(c, NULL, ASL_LEVEL_INFO, "Hello world from py2app launcher");
        asl_log_descriptor(c, msg, ASL_LEVEL_INFO, 1,  ASL_LOG_DESCRIPTOR_WRITE);
        asl_log_descriptor(c, msg, ASL_LEVEL_INFO, 2, ASL_LOG_DESCRIPTOR_WRITE);
}

int main(void)
{
        setup_logging();
        printf("hello world, this is a printf\n");
}

与我的第一次尝试相比,它包含一个更改:它使用asl_log_descriptor的“aslmsg”参数显式设置ASL Facility,Level和ReadUID.如果没有这些参数,消息将不会在Console.app中结束.特别需要ReadUID,以便能够在没有超级用户权限的情况下读取日志条目.

注意:要轻松测试,可以使用“syslog -C | tail”来读取控制台日志.没有ReadUID,当我使用“sudo syslog -C”时,我的程序输出才可见.

相关文章
相关标签/搜索