6
7

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.

「Swiftの自前ログクラス」のSwift3対応版

Last updated at Posted at 2017-01-31

Swift3でのロギングどうしようかな、ライブラリを使うべきかなというところ「Swiftの自前ログクラス」を見つけ試したところ、例によってSwift3ではコンパイルが通らなかった部分がありましたので、Swift3対応版をば。

Usage
Logger.info(message: "init")
>> [INFO] => "init" 2017/01/31 11:11:11 init() MyViewController.swift:(37)

Logger.debug(message: "deinit")
>> [DEBUG] => "deinit" 2017/01/31 12:12:12 deinit() MyViewController.swift:(45)
Logger.swift
import Foundation

class Logger{
    class func debug(
        message: String,
        function: String = #function,
        file: String = #file,
        line: Int = #line) { Logger.write(loglevel: "[DEBUG]", message: message, function: function, file: file, line: line) };
    class func info(
        message: String,
        function: String = #function,
        file: String = #file,
        line: Int = #line) { Logger.write(loglevel: "[INFO]", message: message, function: function, file: file, line: line) };
    class func warning(
        message: String,
        function: String = #function,
        file: String = #file,
        line: Int = #line) { Logger.write(loglevel: "[WARNING]", message: message, function: function, file: file, line: line) };
    class func error(
        message: String,
        function: String = #function,
        file: String = #file,
        line: Int = #line) { Logger.write(loglevel: "[ERROR]", message: message, function: function, file: file, line: line) };
    class func write(
        loglevel: String,
        message: String,
        function: String,
        file: String,
        line: Int) {
        
        let now = NSDate() // 現在日時の取得
        let dateFormatter = DateFormatter()
        dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP") as Locale!
        dateFormatter.timeStyle = .medium
        dateFormatter.dateStyle = .medium
        
        let nowdate = dateFormatter.string(from: now as Date)
        
        var filename = file
        if let match = filename.range(of: "[^/]*$", options: .regularExpression) {
            filename = filename.substring(with: match)
        }
    
        print("\(loglevel) => \"\(message)\" \(nowdate) \(function) \(filename):(\(line))")
    }
}

もっとリッチなロギングが欲しくなったらそのとき考えるということで。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?