NSLogみたいに出力したいけど、出力の頭に入る文字を短く(時間だけに)したい。
SwiftとObjective-Cで同じ出力にしたい。
Swift側
デバッグビルドの設定でSwift Compiler - Custom Flags
> Other Swift Flags
に -D DEBUG
を設定。
ログクラス
public class Log: NSObject {
public static let instance = Log()
private override init() {
dateFormatter = DateFormatter()
dateFormatter.locale = Locale.init(identifier: "en_US_POSIX");
dateFormatter.dateFormat = "HH:mm:ss.SSS"
}
public func print(text: String) {
#if DEBUG
semaphore.wait()
defer {
semaphore.signal()
}
let dateString = dateFormatter.string(from: Date())
Swift.print("[\(dateString)] \(text)")
#endif
}
public func print(format: String, arguments: CVarArg...) {
#if DEBUG
print(format: format, arguments:arguments)
#endif
}
public func print(format: String, arguments: [CVarArg]) {
#if DEBUG
let logLine = String.init(format: format, arguments: arguments)
print(text: logLine)
#endif
}
private let semaphore = DispatchSemaphore(value: 1)
private var dateFormatter: DateFormatter
}
便利関数
public func LOG(_ text: String) {
#if DEBUG
Log.instance.print(text: text)
#endif
}
public func LOG(_ format: String, _ arguments: CVarArg...) {
#if DEBUG
Log.instance.print(format: format, arguments: arguments)
#endif
}
Objective-C側
ログ関数
void _log_print(NSString* format, ...);
#import <MODULE-Swift.h>
void _log_print(NSString* format, ...)
{
va_list args;
va_start(args, format);
NSString* text = [[NSString alloc] initWithFormat:format arguments:args];
va_end(args);
[[Log instance] printWithText:text];
}
prefixヘッダーでNSLog再定義
#if !DEBUG
#define NSLog(...)
#else
#define NSLog(...) _log_print(__VA_ARGS__)
#endif