Search code examples
macosswiftsyslog

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?


Solution

  • 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.