Logging with asl layout on mac OS-X multi-threaded project

331 Views Asked by At

I'd like to convert all my log messages in my multi-threaded project, to use Apple System Log facility (or asl).

according to the following asl manual - https://developer.apple.com/library/ios/documentation/System/Conceptual/ManPages_iPhoneOS/man3/asl_get.3.html

When logging from multiple threads, each thread must open a separate client handle using asl_open.

For that reason, I've defined asl client per thread to be used in all my log commands. However, in facing some major difficulties in binding asl client to each asl_log command.

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.). 

Is there any easier way to adopt my project logging messages to use asl ?

I'd think about something like binding asl client to thread,

thanks

1

There are 1 best solutions below

3
On

Ok, so the best solution I've found out so far is by creating a global variable asl client that is thread-specific.

#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);
}