Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationEventAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.


Logging function with automatic call path/function with CustomDebugStringConvertible

It is convenient to use a static logging function which automatically prints both the values of the parameters, but also details about where the log call was made, to aid debugging.

e.g. call at line 999 in function someFunctionName() in file User/QiitaUser/project/someFileName.swift

log(someDouble, someCustomObject) 

The Xcode Application output is:

someFileName -> line 999 -> someFunctionName -> someDouble, someCustomObject values...

Here, we take advantage the protocol CustomDebugStringConvertible. All native types (string, double) conform to this protocol, and so will show useful information when printing e.g. someDouble.debugDescription, String(reflecting: someDouble). It is also simple to conform custom objects to this protocol in their definition.

See https://developer.apple.com/documentation/swift/customdebugstringconvertible for official implementation details for CustomDebugStringConvertible

// call the function with the "args" paremter only - the other paramters are assigned automatically 
static func log(_ args: Any?..., tag: String = "", file: String = #file, function: String = #function, line: Int = #line) {

// define a value for DEBUG_LOGGING in Build Settings -> Active Compilation Conditions for the debug target

   // extract the calling filename from the complete path, or the complete path, as necessary
   let parsedFileName = String(file.split(separator: "/").last?.split(separator: ".").first ?? "")
   let fileName = (parsedFileName.isEmpty) ? file : parsedFileName

   // extract the calling function name from a string containing the arguments and enclosing brackets
   let functionName = String(function.split(separator: "(").first ?? "")

   // this line defines the location of the log statement
   let header = fileName + "-> line " + String(line) + " -> " + functionName 

   // extract the arguments which conform to CustomDebugStringConvertible, and combine their
   // descriptions via reflection
   let argsAsString = args
      .compactMap{$0 as? CustomDebugStringConvertible}
         String(reflecting: $0).replacingOccurrences(of: "Optional", with: "")
      .joined(separator: " ")

   // print to the Application Output
   Swift.print(text + " " + argsAsString)

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Help us understand the problem. What are the problem?