I'm trying to log function arguments into os_log like this:
func foo(x: String, y: [String:String]) {
//...
os_log("foo: \(x) \(y.description)", log: OSLog.default, type: .debug)
}
But getting error:
Cannot convert value of type 'String' to expected argument type 'StaticString'
So how can I log function arguments, or any other dynamic data?
See Logging:
Formatting Log Messages
To format a log message, use a standard NSString or printf format string, ...
and String Format Specifiers for the standard format string specifiers, such as %# and %d.
In your case:
os_log("foo: %# %#", log: .default, type: .debug, x, y.description)
The format string is restricted to static strings to prevent
(unintentional) expansion of format string specifiers. Here is an example demonstrating the
problem, using NSLog() because that does not restrict the format
to constant strings:
let s = "50%"
NSLog("\(s)percent")
// Output: 500x0ercent
The %p expects a pointer on the variable argument list, which is
not provided. This is undefined behavior, it can lead to crashes
or unexpected output.
In Xcode 12 / Swift 5.3 / iOS 14, you don't have to call os_log directly at all. Instead, replace your use of the OSLog class with the new Logger class (available when you import os). Here's an example:
let myLog = Logger(subsystem: "testing", category: "exploring")
You can then call a method directly on your Logger object to log with that subsystem and category:
myLog.log("logging at \(#function)")
To log at a level other than the default, use that level as the name of the method:
myLog.debug("logging at \(#function)")
In the message string, as you can see, Swift string interpolation is legal. It is allowed for Int, Double, Objective-C objects with a description, and Swift objects that conform to CustomStringConvertible.
The legality of Swift string interpolation here is surprising, because the point of os_log format specifiers is to postpone evaluation of the arguments, pushing it out of your app (so that your app is not slowed down by logging) and into the logging mechanism itself. Well, surprise! Thanks to the custom Swift string interpolation hooks that were introduced in Swift 5, the interpolation is postponed.
And the use of custom string interpolation has two further benefits here. First, the custom string interpolation mechanism allows an interpolation to be accompanied by additional parameters specifying its behavior. That's how you prevent a value from being redacted:
myLog.log("logging at \(#function, privacy: .public)")
You can also use additional parameters to perform various sorts of string formatting that you would otherwise have had to perform using NSLog format specifiers, such as dictating the number of digits after the decimal point and other sorts of padding and alignment:
myLog.log("the number is \(i, format: .decimal(minDigits: 5))") // e.g. 00001
So you'll never need to call os_log directly again, and you won't have to use the NSLog-type format specifiers any more.
OLD ANSWER FOR iOS 13 AND BEFORE:
Two points expanding on Martin R's answer:
os_log("foo: %# %#", log: .default, type: .debug, x, y.description)
You can omit the type: parameter, but you cannot omit the log: parameter; you must have it, including the log: label, or os_log will misinterpret your intentions.
Also, the log: value does not have to be .default. It is usual to create one or more OSLog objects up front, to use as the argument to the log: parameter. The advantage here is that you get to specify the Subsystem and Category for the OSLog object, and these in turn permit you to filter on the results, in the Xcode console or the Console application.
Also, with regard to pkamb's answer, if we know our message is always going to be a string, we can write the OSLog extension like this (taking advantage of the new Swift 5.2 callAsFunction method):
extension OSLog {
func callAsFunction(_ s: String) {
os_log("%{public}s", log: self, s)
}
}
The result is that we can now treat our OSLog object myLog itself as a function:
myLog("The main view's bounds are \(self.view.bounds)")
That's nice because it's as simple as a basic print statement. I appreciate that the WWDC 2016 warns against that sort of preformatting, but if it's what you were already doing in a print statement I can't imagine it's all that harmful.
This is my approach:
import Foundation
import os.log
struct Log {
enum LogLevel: String {
case error = "⛔️"
case warning = "⚠️"
case debug = "💬"
}
static func debug(_ info: String, level: LogLevel = .debug, file: String = #file, function: String = #function, line: Int = #line) {
os_log("%# %#:%d %#: %#", type: .default, level.rawValue, (file as NSString).lastPathComponent, line, function, info)
}
static func warning(_ info: String, level: LogLevel = .warning, file: String = #file, function: String = #function, line: Int = #line) {
os_log("%# %#:%d %#: %#", type: .default, level.rawValue, (file as NSString).lastPathComponent, line, function, info)
}
static func error(_ error: NSError, level: LogLevel = .error, file: String = #file, function: String = #function, line: Int = #line) {
os_log("%# %#:%d %#: %#", type: .default, level.rawValue, (file as NSString).lastPathComponent, line, function, "\(error)")
}
}
Usage:
Log.debug("MyLog")
Output example:
💬 AppDelegate.swift:26 application(_:didFinishLaunchingWithOptions:): MyLog
I was getting annoyed at not being able to use "\(variable)" Swift string interpolation in os_log.
I wrote a small extension to get around the issue:
import os.log
extension OSLog {
static func log(_ message: String, log: OSLog = .default, type: OSLogType = .default) {
os_log("%#", log: log, type: type, message)
}
}
This does cause "private" logging, which is expected.
App Name <private>
In Console.app, how can I reveal to what <private> tags are actually referring?
In Apple's WWDC 2016 presentation "Unified Logging and Activity Tracing" they say:
Avoid wrapping os log APIs in other functions.
If you wrap it in another function you then lose our ability to collect the file and line number for you.
If you absolutely have to wrap our APIs, then wrap them in macros and not in functions.
So this is perhaps not the best solution if you are concerned about additional collected information. Although that information still may not be available even using stock os_log: How to find source file and line number from os_log()
A "macro" alternative that allows "\(variable)" substitution would be welcome if anyone want to write it.
The macOS 11 Big Sur Release Notes state that os_log can now be passed Swift string interpolation:
https://developer.apple.com/documentation/macos-release-notes/macos-big-sur-11-beta-release-notes
Logging
New Features
New APIs are available for using os_log from Swift as part of the os framework:
A new type Logger can be instantiated using a subsystem and category and provides methods for logging at different levels ( debug(_:) , error(_:) , fault(_:) ).
The Logger APIs support specifying most formatting and privacy options supported by legacy os_log APIs.
The new APIs provide significant performance improvements over the legacy APIs.
You can now pass Swift string interpolation to the os_log function.
Note: The new APIs can't be back deployed; however, the existing os_log API remains available for back deployment. (22539144)
Related
I am using CocoaLumberjack for a Swift project. I would like to implement custom log levels/flags, as I would like to use 6 rather than the default 5, and would prefer different names.
The documentation for doing this is not helpful. It is only a solution for Objective-C.
The fact that DDLogFlag is defined as NS_OPTIONS means I actually could simply ignore the pre-defined values here, create my own constants, and just write some wrapping code to convert from one to the other.
However, DDLogLevel is defined as NS_ENUM, which means Swift won't be very happy with me trying to instantiate something to say 0b111111, which isn't an existing value in the enum. If it were an NS_OPTIONS, like DDLogFlag, I could just ignore the pre-existing definitions from the library and use whatever valid UInt values I wanted to.
As far as I can tell, I just have to write some Objective-C code to define my own replacements for DDLogLevel, DDLogFlag, and write a custom function to pass this in to and access these properties on DDLogMessage. But this feels bad.
How can I use my own custom logging levels in Swift with CocoaLumberjack?
This is indeed only possible in Objective-C right now - and there also only for the #define Log Macros. Even then I could imagine that the "modern" ObjC compiler will warn about the types that are passed to DDLogMessage.
The docs are indeed a bit outdated here and stem from a time where Objective-C was closer to C that it is to Swift nowadays... :-)
Nevertheless, in the end DDLogLevel and DDLogFlag are both stored as NSUInteger. Which means it can theoretically take any NSUInteger value (aka UInt in Swift).
To define your own levels, you would simply create an enum MyLogLevel: UInt { /*...*/ } and then write your own logging functions.
Those functions can actually forward to the existing functions:
extension DDLogFlag {
public static let fatal = DDLogFlag(rawValue: 0x0001)
public static let failure = DDLogFlag(rawValue: 0x0010)
}
public enum MyLogLevel: UInt {
case fatal = 0x0001
case failure = 0x0011
}
extension MyLogLevel {
public static var defaultLevel: MyLogLevel = .fatal
}
#inlinable
public func LogFatal(_ message: #autoclosure () -> Any,
level: MyLogLevel = .defaultLevel,
context: Int = 0,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line,
tag: Any? = nil,
asynchronous async: Bool = asyncLoggingEnabled,
ddlog: DDLog = .sharedInstance) {
_DDLogMessage(message(), level: unsafeBitCast(level, to: DDLogLevel.self), flag: .fatal, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
The unsafeBitCast here works, because in the end it's just an UInt and _DDLogMessage does not switch over the level, but instead does a bit mask check against the flag.
Disclaimer: I'm a CocoaLumberjack maintainer myself.
We don't recommend using a custom log level in Swift. There's not much benefit from it and logging frameworks like swift-log also use predefined log levels.
However, I personally could also imagine declaring DDLogLevel with NS_OPTIONS instead of NS_ENUM. The OSLog Swift overlay also uses an extensible OSLogType.
If this is something you'd like to see, please open a PR so we can discuss it with the team. We need to be a bit careful with API compatibility, but like I said it's totally doable.
On a side-note: May I ask what you need custom levels for?
In Swift 3, what is the recommended way to put (potentially lots of) additional information in an error/exception that the catcher can use to solve/handle the problem? In all the examples I've seen, they use enums with associated values, and that seems overly cumbersome/verbose for lots of information.
Specifically, I am writing a simple parser and want a place to store the affected line and column numbers (and potentially other information in the future), but without requiring that every handler explicitly declare those as associated values, as that would be a burden on the caller.
At this point I can basically see two ways of doing this, neither of which seems particularly elegant and both of which require defining two different things:
Define an outer enum error that represents the type of error, and for each case accept a parameter that is an object that contains the additional exception details, or
Use the object as the actual Error and pass in a case from an enum to its constructor to represent the actual error condition.
Both of these feel somewhat unclean to me though as they take two separate concepts to represent a simple idea, an error, and I'm just wondering if there's a nicer way to do this.
Are there any conventions or recommended ways to handle errors that need to contain potentially lots of additional information?
I don't know if there is a "recommended" way, perhaps someone else can
answer that or provide a better solution.
But one possible approach would be to use a struct (with properties) as the error type and use optional properties for values which need
not be provided. Example:
struct ParserError: Error {
enum Reason {
case invalidCharacter
case unexpectedEOF
}
let reason: Reason
let line: Int?
let column: Int?
init(reason: Reason, line: Int? = nil, column: Int? = nil) {
self.reason = reason
self.line = line
self.column = column
}
}
One might also want to adopt the LocalizedError protocol to
provide sensible error descriptions even if the
concrete error type is not known by the catcher (compare How to provide a localized description with an Error type in Swift?):
extension ParserError: LocalizedError {
public var errorDescription: String? {
var description: String
switch reason {
case .invalidCharacter:
description = "Invalid Character in input file"
case .unexpectedEOF:
description = "Unexpected end of file"
}
if let line = line {
description += ", line \(line)"
}
if let column = column {
description += ", column \(column)"
}
return description
}
}
Usage example:
func parse() throws {
// Throw error with line number, but without column:
throw ParserError(reason: .invalidCharacter, line: 13)
}
do {
try parse()
} catch let error {
print(error.localizedDescription)
}
Output:
Invalid Character in input file, line 13
I want to log all controller methods calls including methodname, methodparams and dont want to write a log to each method. It should handle from one point. is it possible to write interceptor or aspect in swift?
ex. 2016-05-05 09:47:33.927 xxx[58787:27517992] init() method called with params ["xxx", "yyy"]
Thanks.
For Swift >=2.2:
You can try to do:
print("\(NSDate()) \(#file) \(#line) \(#function) in \(self.dynamicType)")
You can use a global method like this:
func VerboseLog<T>(object: T, filename: String = #file, line: Int = #line, funcname: String = #function) {
print("\(NSDate()) \(filename) \(line) \(funcname) in \(object.dynamicType)")
}
More information:
#file - String - The name of the file in which it appears.
#line - Int - The line number on which it appears.
#column - Int - The column number in which it begins.
#function - String - The name of the declaration in which it appears.
Apple official source.
About aspect oriented programming as you ask, unfortunately Swift dont has now a runtime support. You must refer to obj-c bridging.
There is an interesting library called MOAspect that can be useful if you want to use this kind of approach:
MOAspects.hookClassMethodForClass(UIScreen.self, selector:"mainScreen", position:.Before) {
NSLog("hooked screen!")
}
UIScreen.mainScreen() // -> hooked screen!
I'm looking to implement some simple string templating in Swift and am wondering what the built-in options are for replacing macros in a string with values at runtime.
It would be awesome if there were a way for me to use the string interpolation syntax "\(variable)" at runtime, but I'm guessing these are actually parsed at compile time since the macros can contain actual code.
I've also found a String constructor that accepts a format string in Objective-C style, using %#, etc.
let myString = String(format: "Hello %#", name)
That could work, though I like the syntax less. I'm just wondering if there are better approaches I should take, or if it would be better to just write my own.
Being able to execute commands (like operators or method/property calls) within the macro would be awesome, but not required (and considering how static a language Swift is, not expected).
import Foundation
let serverName = "Fantastic"
var resultString = "We are using $SERVERNAME$"
if let range = resultString.rangeOfString("$SERVERNAME$") {
resultString.replaceRange(range, with: serverName)
}
You could, of course, implement a String extension if you are going to be using this regularly.
extension String {
func replaceString(sourceString:String, withNewElements newElements:String) throws {
//implementation left for the reader
let userInfo = ["missingString": sourceString,
"message": "Substring '\(sourceString)' not found in '\(self)'"]
throw NSError(domain: "ReplaceStringFailure", code: 1, userInfo: userInfo)
}
}
I'm trying to write a function that takes a parameter of type Printable:
func logMessage(message: Printable) {
// ...
}
Strangely, this doesn't work as expected when passing in Strings.
This doesn't compile:
logMessage("some string \(someVariable)")
// Neither does this:
let aString = "aString"
logMessage(aString)
This however compiles:
logMessage("A string")
// This works too:
let aString: Printable = "a string"
logMessage(aString)
This is quite confusing. It seems that in some cases String implements Printable and in others not.
In addition, it seems that string interpolation always produces a String that does not implement Printable. This crashes at runtime with a cast error:
let aString = "a string"
let interpolatedString = "contains \(aString)"
Any idea what's going on here?
You're right that String doesn't conform to Printable. The reason this compiles:
let aString: Printable = "Ceci n'est pas une String"
is that you aren't creating a String with that literal – you're creating an NSString (which is Printable).
Generally, in Swift, it’s usually better to write generic functions constrained by protocols. So instead of
func logMessage(message: Printable) {
// ...
}
you would probably be better off writing:
func logMessage<T: Printable>(message: T) {
// ...
}
This approach has a number of advantages – better type-safety and avoiding type erasure, more performant etc. You can read more about this stuff here.
But you'll still hit a problem because you can't pass in a String. You have two options here. First, just don't constraint it at all:
func logMessage<T>(message: T) {
// ...then use toString(message) to create a String if you need one,
// or use string interpolation or print()
}
This will work with String, and in fact will also work with anything that isn’t Printable as well (though you'll get quite a unhelpful output involving the mangled classname).
Or, you could use Streamable which strings do conform to:
func logMessage<T: Streamable>(message: T) {
println(message)
}
let s: String = "hello"
logMessage(s)
I think I read a while back on twitter one of the Swift team mention that the reason String doesn't conform to Printable is exactly because they didn't want people using Printable directly like this and that it’s better to always use toString or similar.