1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

デバッグ時だけログを吐き出す便利なラッパークラス

1
Posted at

本記事を書く背景

QiitaでNSLogを使ったデバッグログの吐き方についての記事をみて、
本番ユーザさんにもNSLogだと参照される危険があるな〜と感じたので、
個人的に使っているデバッグ時にだけログを吐き出すログ用のラッパーを紹介します。

環境

  • Xcode 10.2
  • Swift 5.0

実装

プリプロセッサマクロを利用してDEBUGに設定しているスキームのときだけログを吐き出すようなメソッドとなっています。
printの部分はよしなにNSLogに差し替えても構いません。
通常エラーが発生してほしくない場合にログを吐き出す場合はerrorのメソッドを利用すると良いです。
発生した ファイル名、メソッド、行数を自動で吐き出します。

以下、テンプレとしてお使いいただければと思います。


struct Logger {
  
  /// デバッグ時だけログを吐き出すメソッド
  static func debug(_ item: Any) {
    #if DEBUG
    print(item)
    #endif
  }
  
  /// エラーパターンに埋め込むメソッド
  static func error(file: String = #file, function: String = #function, line: Int = #line, _ message: String = "") {
    #if DEBUG
    let consolLog = "file: \(file)\n function: \(function)\n line: \(line)\n message: \(message)\n"
    print(consolLog)
    #endif
  }
  
}

最後に

もっとこうした方がいいよ、間違えている箇所あるよ
等はご指摘いただけると助かります!

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?