ASL: Logging

2008-01-20 13:48:14 UTC

ASL provides two ways to write to the log.

The first, and most recognizable, way is the asl_log pair of functions:

int asl_log(aslclient asl, aslmsg msg, int level, const char *format, ...);
int asl_vlog(aslclient asl, aslmsg msg, int level, const char *format, va_list ap);

The last two arguments (format, and .../ap) are the same as the arguments to printf/vprintf or syslog/vsyslog. They’re also similar to NSLog/NSLogv, except that ASL does not support %@ in its format strings.

The first two arguments to asl_log are optional. If you pass NULL as the client, it uses a default connection with default settings. If you pass NULL for the message, all of the message’s properties other than the level and content will have their default values. Normally, you will pass NULL for the first two arguments.

The argument in the middle, level, specifies the importance of the message. It works exactly the same way as syslog(3)’s priority argument; in fact, they use the same values, and those values have the same names.

If you don’t feel like changing over all your NSLog calls to use asl_log because you’ll have to change your format strings to use %s and -UTF8String instead of %@, don’t worry. Here’s a one-line macro you can stash in a header file to give you an asl_log-like NSLog:

#define asl_NSLog(client, msg, level, format, ...) asl_log(client, msg, level, "%s", [[NSString stringWithFormat:format, ##__VA_ARGS__] UTF8String])

This macro gives you all the flexibility of asl_log and all the format specifiers of NSLog.

The other way to write to the log is to construct a message object yourself and send the whole thing.

ASL defines a type called aslmsg, which is little more than a key-value mapping. All keys and values are UTF-8 C strings. ASL provides and uses several stock keys for the normal properties of a message:

ASL_KEY_LEVEL
The priority level of the message, expressed as the decimal representation of an integer (ASL_LEVEL_*). When setting this property, you can use the level-name strings (ASL_STRING_*) here; they are names, not numbers, but they will be translated to the correct values for you.

2 Responses to “ASL: Logging”

  1. Hans van der Meer Says:

    I do not have not so much as a reply, but a question.

    Using XCode 3.0 (Leopard) I coded:
    asl_log(NULL, NULL, 1, “TESTING ASL-LOG:%s”, “asl-log test”);
    but do not see anything resulting from it.
    Neither in the XCode console, nor in the Console app. Why not?
    Am I doing something wrong?

  2. Peter Hosey Says:

    Hans van der Meer:

    For how to make it appear in Xcode, read the next post, Client connections.

    For how to make it appear in Console, first read the section on ASL_KEY_FACILITY, then read Client connections (you can set the default facility of every message with a client connection).

    Reading the entire series is a good idea in general. ☺

Leave a Reply

Do not delete the second sentence.