How can I use `syslog` in Swift

2019-05-05 20:36发布

Looks like syslog() function is not available in Swift 2.

How can I send a message to syslog on OS X?

1条回答
Anthone
2楼-- · 2019-05-05 21:14

The problem is that

void syslog(int priority, const char *message, ...);

takes a variable argument list and is not imported to Swift. You can use

void vsyslog(int priority, const char *message, va_list args);

instead and define a wrapper function in Swift:

func syslog(priority : Int32, _ message : String, _ args : CVarArgType...) {
    withVaList(args) { vsyslog(priority, message, $0) }
}

syslog(LOG_ERR, "i=%ld, x=%f", 123, 34.56)

Note that string arguments have to be passed as C strings:

syslog(LOG_ERR, "status=%s", "OK".cStringUsingEncoding(NSUTF8StringEncoding))

Alternatively, use NSLog() which writes to the system log as well:

NSLog("i=%ld, x=%f, status=%@", 123, 34.56, "OK")

Note also that on OS X, syslog() is just a wrapper to the "Apple System Logger facility". You can call the asl_XXX functions directly, you only have to #include <asl.h> in the bridging header file. As above, asl_log() is not imported to Swift and you have to call asl_vlog() instead.

查看更多
登录 后发表回答