Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use `syslog` in Swift

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

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

like image 549
Valentin Shergin Avatar asked Oct 31 '22 17:10

Valentin Shergin


1 Answers

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.

like image 79
Martin R Avatar answered Nov 15 '22 06:11

Martin R