5

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

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

Valentin Shergin
  • 7,166
  • 2
  • 50
  • 53

1 Answers1

2

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Awesome! Thank you! I have found `vsyslog` but I had not idea how work with `CVaListPointer`. – Valentin Shergin Oct 18 '15 at 06:42
  • @ValentinShergin: You are welcome. – Re your edit: You were right about the typo. But `message : String` was intentional and works because a Swift string is converted automatically when passed to a C function taking a `const char *` parameter, compare http://stackoverflow.com/questions/27063569/string-value-to-unsafepointeruint8-function-parameter-behavior. – Martin R Oct 18 '15 at 07:03
  • Yes, I realised that I was wrong after I send the edit, but there is no way to cancel edit on SO. Sorry for the mess. :( Swift is awesome, you are awesome too. – Valentin Shergin Oct 18 '15 at 07:08