Why print() in Swift does not log the time stamp as NSLog in objective C
Asked Answered
P

6

52

From background of Objective C when I use NSLog() it prefixes the text with the date time stamp, but when I use print() on Swift it only prints the text

So it there is a way to make it print the time stamp as well, or am I doing some thing wrong?

Perpend answered 27/10, 2015 at 9:45 Comment(4)
I'm not particularly sure, but I'm pretty sure this has to do with the fact that NSLog prints to the Console (and your log is visible in Console.app) but print in Swift doesn't do that.Hhd
I have no evidence to support this 2nd point, but I believe that Xcode actually takes information from the Console and prints everything in a certain category even if it's not related to the program you're running. I've seen some irrelevant console messages in my Xcode. Maybe Swift's print just prints to the Xcode console?Hhd
check this question: #25951695Tiros
Note that whichever solution you choose, NSLog will print output to the console in a release build while print will not. Choose wisely.Claudette
P
66

Because print is not NSLog. It is as simple as that.

NSLog is a logging tool in Foundation that writes to the Apple System Log facility which appears on the console.

print(…) is a print function in the Swift Standard Library that writes to standard out, which appears on the console in debug sessions.

You could add Date() to your print parameter to print the current time and date. (Or Date().description(with: Locale.current) to get it in your local time zone.)

Or you could just use NSLog which is available in Swift too (if you import Foundation).

Prelacy answered 27/10, 2015 at 9:51 Comment(1)
Thanks I tried NSLog and it works so I'll work with it in the cases that I need to show the time stampPerpend
L
37

Swift:

NSLog("this will print with dates")
Leper answered 23/12, 2015 at 23:48 Comment(4)
But not printing in PlaygroundDemetrademetre
@Demetrademetre have you tried importing Foundation? thanks for the tip anyway.Leper
@Tillus have you tried importing Foundation? this will only work if there is a obj-c runtime, it is not the case in a playground.Leper
Yes with implementing foundation it is the same. I think OSLog should be used nowCartercarteret
D
12

This one just outputs a simple timestamp, but can be easily modified to include additional text if you want.

Additionally, it relies on a lazy DateFormatter to avoid expensive initializations.

import Foundation

class Timestamp {
    lazy var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS "
        return formatter
    }()

    func printTimestamp() {
        print(dateFormatter.string(from: Date()))
    }
}

let timestamp = Timestamp()
timestamp.printTimestamp() // 2018-07-05 12:57:08.725
timestamp.printTimestamp() // 2018-07-05 12:57:08.727 (uses the same formatter)
Duchamp answered 5/7, 2018 at 19:59 Comment(1)
This is one of the correct answers. Note that NSLog will print output to the console in a release build while print will not.Claudette
E
8

Here is a suggested function you can use instead of print()

func printLog(log: AnyObject?) {
    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS "
    print(formatter.stringFromDate(NSDate()), terminator: "")
    if log == nil {
        print("nil")
    }
    else {
        print(log!)
    }
}
Exeat answered 5/7, 2016 at 21:46 Comment(2)
Creating an instance of NSDateFormatter is costly. So, ideally, the formatter would have to be created only once, outside your method, to avoid calling NSDateFormatter() each time the method is called.Hepza
It is not about what you want - in this case, this should be done.Berard
E
4

iOS 14+

New API os.Logger.log with optional level parameter: https://developer.apple.com/documentation/os/logger/3551622-log

import os.Logger

log("Message \(var)")
log(level: .debug, "Message \(var)")

Deprecated ⚠️

You can use the Logging os module to do that in Swift: https://developer.apple.com/documentation/os/logging

Specifically os_log: https://developer.apple.com/documentation/os/2320718-os_log

import os.log
os_log("Message %d", type: .info, value)
Eosinophil answered 11/11, 2020 at 16:23 Comment(2)
os_log already seems to be deprecatedDorser
ty @PeterKreinz, updated accordinglyEosinophil
A
2

Make your own class function for print, eg printWithDate() and prepend the date to the output. Then you can use this everywhere without needing to add the date each time you want to print.

Anguished answered 27/10, 2015 at 9:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.