【问题标题】:Logging with asl layout on mac OS-X multi-threaded project在 mac OS-X 多线程项目上使用 asl 布局进行日志记录
【发布时间】:2015-12-04 17:09:29
【问题描述】:

我想将我的多线程项目中的所有日志消息转换为使用 Apple 系统日志工具(或 asl)。

根据以下 asl 手册 - https://developer.apple.com/library/ios/documentation/System/Conceptual/ManPages_iPhoneOS/man3/asl_get.3.html

从多个线程记录时,每个线程必须使用 asl_open 打开一个单独的客户端句柄。

出于这个原因,我为每个线程定义了 asl 客户端,以便在我的所有日​​志命令中使用。但是,在将 asl 客户端绑定到每个 asl_log 命令时面临一些重大困难。

1. what if some of my asl log commands reside in a code that is common for
   more than one thread - which asl client should i decide use on such message.

2. Even on thread unique code, one should be consistent in choosing the same
   asl_client on all log functions on a single thread code scope (this is
   not always easy to find in complex projects.). 

有没有更简单的方法来采用我的项目日志消息来使用 asl ?

我会考虑将 asl 客户端绑定到线程,

谢谢

【问题讨论】:

  • 糟糕的标题,类似的问题!
  • @πάντα ῥεῖ 感谢您的反馈。我修改了标题和消息。希望新的措辞更全面。

标签: c++ c macos logging asl


【解决方案1】:

好的,到目前为止,我发现的最佳解决方案是创建一个特定于线程的全局变量 asl 客户端。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <asl.h>
#define NUMTHREADS 4

pthread_key_t glob_var_key;

void print_func() //take global var and use it as the aslclient per thread
{ 
    asl_log(*((aslclient*) pthread_getspecific(glob_var_key)),NULL,ASL_LEVEL_NOTICE, "blablabla");
}

void* thread_func(void *arg)
{
    aslclient *p = malloc(sizeof(aslclient));
    // added tid to message format to distinguish between messages 
    uint64_t tid;
    pthread_threadid_np(NULL, &tid);
    char tid_str[20];
    sprintf(tid_str, "%llu", tid);

    *p = asl_open(tid_str,"Facility",ASL_OPT_STDERR);
    pthread_setspecific(glob_var_key, p);
    print_func();

    sleep(1); // enable ctx switch

    print_func();

    pthread_setspecific(glob_var_key, NULL);
    free(p);
    pthread_exit(NULL);
}


int main(void)
{
    pthread_t threads[NUMTHREADS];
    int i;

    pthread_key_create(&glob_var_key,NULL);
    for (i=0; i < NUMTHREADS; i++)
        pthread_create(&threads[i],NULL,thread_func,NULL);

    for (i=0; i < NUMTHREADS; i++)
        pthread_join(threads[i], NULL);
}

【讨论】:

  • 如果你使用的是 C++11,你可以利用 __thread 并这样做:__thread aslclient client;
  • @Petesh,也许你可以给我一些使用参考,因为我在网上没有找到任何有用的东西。非常感谢!
  • 它的作用是自动使值线程本地化——您不需要涉及任何 pthread_getspecific 或 pthread_setspecific 代码;只需 asl_open 在开头,asl_close 在线程末尾。 C++11 标准说只使用thread_local;但是我没有让它在 OSX 上正常工作,而 __thread 只要您使用提供的 libc++ (这是最近几个版本的默认 c++ 标准库)就可以正常工作
猜你喜欢
  • 2015-12-16
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
相关资源
最近更新 更多