How can I use `syslog` in Swift

半世苍凉 提交于 2019-12-05 14:27:39

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!