LoginSignup
4
7

More than 5 years have passed since last update.

Swiftでの関数名出力なども添えたデバッグログ関数

Last updated at Posted at 2018-07-24

何度も煎じられた話かと思います。
が、Swift経験の浅い身には戸惑う事も多かったため、自分用にまとめておきます。

Log.swift
import Foundation

func debugLog(_ message: String = "", function: String = #function, file: String = #file, line: Int = #line) {
    #if DEBUG
        let fileName = URL(string: file)!.lastPathComponent
        NSLog("\(fileName) #\(line) \(function): \(message)")
    #endif
}
Example.swift
func testDebugLog(){
    let world = "https://swift.org"
    debugLog("hello, \(world)")
    let optWorld = URL(string: "https://swift.org")
    debugLog("hello, \(String(describing: optWorld))")
}
2018-07-24 23:36:51.553728+0900 DemoDebugLog[10270:2333830] main.swift #30 testDebugLog(): hello, https://swift.org
2018-07-24 23:36:51.556192+0900 DemoDebugLog[10270:2333830] main.swift #33 testDebugLog(): hello, Optional(https://swift.org)

簡単な解説

  • __FUNCTION__ で取得していたのは昔の話です。Swift2.2での仕様改定により #file #function #line などのリテラルに置き換えられました。これらのリテラルは、引数のデフォルト値として設定した場合に特殊な扱いとなり、関数を呼び出した箇所に基づく値が設定されます。

  • ログを出力したソースコード箇所を特定可能とするために #file#line の値を出力します。#fileの値はビルド環境における絶対パスです。このままではログ出力として長すぎるためlastPathComponentによりファイル名を抽出します。

  • 上述のコードではNSLog()でログ出力していますが、あとはお好みで print()os_log() に置き換えてください。

  • この記事はSwift4.1時点の情報に基づきます。

参考リンク

Swift > Language Reference > Expressions > Literal Expression
https://docs.swift.org/swift-book/ReferenceManual/Expressions.html

Documentation > Swift > Swift Standard Library > Debugging and Reflection
https://developer.apple.com/documentation/swift/swift_standard_library/debugging_and_reflection

swiftでデバッグログ
https://qiita.com/sasho/items/d19ba6d835b9ea9d9e81
Swiftでクラス名や関数名等をログ出力する
https://qiita.com/shtnkgm/items/de9cf3d85ccd0cef0a81
「Swiftの自前ログクラス」のSwift3対応版
https://qiita.com/hirocueki2/items/643c05819039a4120c68#_reference-de88920dc6f524d73829
Swift 2.2 で変わったところ
https://qiita.com/es_kumagai/items/df8cf82ec621558d653c#%E3%82%BD%E3%83%BC%E3%82%B9%E3%82%B3%E3%83%BC%E3%83%89%E3%81%AE%E4%BD%8D%E7%BD%AE%E3%81%AB%E9%96%A2%E3%81%99%E3%82%8B%E6%83%85%E5%A0%B1
マジレスすると『Optional(2018)年』を恐れる必要はない
https://qiita.com/koher/items/6c855ddbda8797af4605
Swift: print() vs println() vs NSLog()
https://stackoverflow.com/questions/25951195/swift-print-vs-println-vs-nslog/25951564
[iOS 10] os_logを使ったLoggerを作ってみた
https://dev.classmethod.jp/smartphone/iphone/ios-10-os-log-logger/

4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7