swift print()到控制台日志

5w9g7ksd  于 2023-04-19  发布在  Swift
关注(0)|答案(8)|浏览(134)

代码为:

let redColor = "\u{001B}[0;31m"
var message = "Some Message"
print(redColor + message)  //This doesn't work
print("\(redColor)\(message)") //This also doesn't work

输出如下所示:

[0;31mSome Message

我也读过这篇文章:Color ouput with Swift command line tool,它似乎不工作。
我不想使用图书馆。

7d7tgy0s

7d7tgy0s1#

Xcode console color theme/scheme

Go to Preferences > Fonts and Colors
Select Console at top of window
Then select the color for Executable console output
plupiseo

plupiseo2#

根据Mojtaba Hosseini的回答,我将其合并到一个Log类中,以获得非常详细的日志记录:
类如下:

import Foundation
import OSLog

class Log {
    #if DEBUG
    static let logLevel = "deiwv"
    #else
    static let logLevel = "e"
    #endif
    static var subsystem = Bundle.main.bundleIdentifier ?? ""
    static var flags = [  "e" : "📕",
                        "w" : "📙",
                        "i" : "📗",
                        "d" : "📘",
                        "v" : "📓"
                  ]
    
    static func setup(_ fileStr: String, _ funcStr: String, _ line: Int, _ level: String) -> String {
        var fileName = fileStr.components(separatedBy: "/").last ?? ""
        fileName = fileName.components(separatedBy:".").first ?? ""
        fileName = fileName.padding(toLength: 20, withPad: " ", startingAt: 0)
        let funcString = funcStr.padding(toLength: 10, withPad: " ", startingAt: 0)
        let lineNum = "\(line)".padding(toLength: 4, withPad: " ", startingAt: 0)
        let flag = flags[level] ?? ""
        return "\(flag)\(level.uppercased()) \(fileName):\(funcString):\(lineNum)"
    }
    
    static func i(_ msg: String, fileStr: String = #file, funcStr: String = #function, line: Int = #line) {
        if(logLevel.contains("i")) {
            Logger(subsystem: subsystem, category: setup(fileStr, funcStr, line, "i")).info("\(msg)")
        }
    }
    static func e(_ msg: String, fileStr: String = #file, funcStr: String = #function, line: Int = #line) {
        if(logLevel.contains("e")) {
            Logger(subsystem: subsystem, category: setup(fileStr, funcStr, line, "e")).error("\(msg)")
        }
    }
    static func d(_ msg: String, fileStr: String = #file, funcStr: String = #function, line: Int = #line) {
        if(logLevel.contains("d")) {
            Logger(subsystem: subsystem, category: setup(fileStr, funcStr, line, "d")).debug("\(msg)")
        }
    }
    static func w(_ msg: String, fileStr: String = #file, funcStr: String = #function, line: Int = #line) {
        if(logLevel.contains("w")) {
            Logger(subsystem: subsystem, category: setup(fileStr, funcStr, line, "w")).warning("\(msg)")
        }
    }
    static func v(_ msg: String, fileStr: String = #file, funcStr: String = #function, line: Int = #line) {
        if(logLevel.contains("v")) {
            Logger(subsystem: subsystem, category: setup(fileStr, funcStr, line, "v")).log("\(msg)")
        }
    }
}

这允许记录,即如下:

Log.i("This is the logged comment")

Log.e("This is an error")

输出被标记,并显示文件名,函数名和发生日志记录的行号,使其更容易在较大的项目中找到一些东西:

2023-04-12 19:03:22.006185+0100 OOHSystem[34170:6047034] [📗I InitialViewControlle:viewDidLoa:27  ] Loaded
2023-04-12 19:03:22.006766+0100 OOHSystem[34170:6047034] [📗I InitialViewControlle:viewWillAp:33  ] Started
2023-04-12 19:03:22.007867+0100 OOHSystem[34170:6047034] [📗I InitialViewControlle:viewWillAp:47  ] Called from startup
2023-04-12 19:03:22.078324+0100 OOHSystem[34170:6047034] [📗I UIDeviceExtensions  :UIDevice  :110 ] identfied: arm64
2023-04-12 19:03:22.079177+0100 OOHSystem[34170:6047034] [📓V Globals             :token     :17  ] 3ae51797ac5a8619010352's

默认情况下,生产只记录错误,当然这很容易配置。
可能有更好或更优雅的方法来实现这一点,但它对我有效。

bybem2ql

bybem2ql3#

自Xcode 8起,Xcode不支持控制台着色。
但是由于Xcode是完全兼容unicode的,你可以使用emojis代替!例如,你可以使用⚠️作为警告消息,🛑作为错误消息。(就像Xcode本身一样)
或者简单地把这些笔记本当作一种颜色:

📕: error message
📙: warning message
📗: ok status message
📘: action message
📓: canceled status message
📔: Or anything you like and want to recognize immediately by color

例如:

print("⚠️", "Touch is not disabled as expected")

🎁骨头

使用这种方法将帮助您通过简单的眼睛扫描以最快的速度找到源代码中的日志️:

你可以搜索它们📱👁,让Xcode带你去那里。看看这个结果比较:

自定义表情搜索

vs

单词搜索

eagi6jfj

eagi6jfj4#

目前,Xcode调试控制台不支持着色。

vsikbqxv

vsikbqxv5#

添加到@Mojtaba的答案中,您可以使用以下内容来自动化日志记录:

enum LogType: String{
case error
case warning
case success
case action
case canceled
}

class Logger{

 static func log(_ logType:LogType,_ message:String){
        switch logType {
        case LogType.error:
            print("\n📕 Error: \(message)\n")
        case LogType.warning:
            print("\n📙 Warning: \(message)\n")
        case LogType.success:
            print("\n📗 Success: \(message)\n")
        case LogType.action:
            print("\n📘 Action: \(message)\n")
        case LogType.canceled:
            print("\n📓 Cancelled: \(message)\n")
        }
    }

}

你可以这样使用它:

Logger.log(.error, "Invalid Credit Information")
cu6pst1q

cu6pst1q6#

正如@LeslieGodwin提到的,XcodeColors Xcode插件为Xcode控制台增加了颜色支持**(适用于8以下的Xcode版本)**

djmepvbi

djmepvbi7#

添加自己的贡献:

struct Logger {
    /// Type of logs available
    enum LogType: String {
        /// To log a message
        case debug
        /// To log a warning
        case warning
        /// To log an error
        case error
    }
    
    /// Logs a debug message
    /// - Parameter message: Message to log
    /// - Parameter file: File that calls the function
    /// - Parameter line: Line of code from the file where the function is call
    /// - Parameter function: Function that calls the functon
    /// - Returns: The optional message that was logged
    @discardableResult
    static func d(message: String, file: String = #file, line: Int = #line, function: String = #function) -> String{
        return log(type: .debug, message: message, file: file, line: line, function: function)
    }
    
    /// Logs a warning message
    /// - Parameter message: Message to log
    /// - Parameter file: File that calls the function
    /// - Parameter line: Line of code from the file where the function is call
    /// - Parameter function: Function that calls the functon
    /// - Returns: The optional message that was logged
    @discardableResult
    static func w(message: String, file: String = #file, line: Int = #line, function: String = #function) -> String{
        return log(type: .warning, message: message, file: file, line: line, function: function)
    }
    
    /// Logs an error message
    /// - Parameter message: Message to log
    /// - Parameter file: File that calls the function
    /// - Parameter line: Line of code from the file where the function is call
    /// - Parameter function: Function that calls the functon
    /// - Returns: The optional message that was logged
    @discardableResult
    static func e(message: String, file: String = #file, line: Int = #line, function: String = #function) -> String{
        return log(type: .error, message: message, file: file, line: line, function: function)
    }
    
    /// Logs an message
    /// - Parameter logType: Type of message to log
    /// - Parameter message: Message to log
    /// - Parameter file: File that calls the function
    /// - Parameter line: Line of code from the file where the function is call
    /// - Parameter function: Function that calls the functon
    /// - Returns: The optional message that was logged
    @discardableResult
    static func log(type logType: LogType = .debug, message: String, file: String = #file, line: Int = #line, function: String = #function) -> String{
        var logMessage = ""
        
        switch logType{
        case .debug:
            logMessage += "🟢"
        case .warning:
            logMessage += "🟡"
        case .error:
            logMessage += "🔴"
        }
        
        let fileName = file.components(separatedBy: "/").last ?? ""
        logMessage += " \(fileName) -> LINE: \(line) -> \(function) => \(message)"
        
        print(logMessage)
        return logMessage
    }

}

您可以随时更改图标使用“crtl+cmd+space”

0wi1tuuw

0wi1tuuw8#

如果你想在Xcode中寻找一个替代的颜色日志记录,可以看看我创建的这个新的swift-log特性。
https://github.com/nneuberger1/swift-log-console-colors
它使用新的标准swift-log兼容库。
如果传入.cool,输出将如下所示

2021-05-09T16:13:30-0500 🐛 debug thingsAboveAdmin : Testing log levels..
2021-05-09T16:13:30-0500 ℹ️ info thingsAboveAdmin : Testing log levels..
2021-05-09T16:13:30-0500 📖 notice thingsAboveAdmin : Testing log levels..
2021-05-09T16:13:30-0500 ⚠️ warning thingsAboveAdmin : Testing log levels..
2021-05-09T16:13:30-0500 ⚡ critical thingsAboveAdmin : Testing log levels..
2021-05-09T16:13:30-0500 🔥 error thingsAboveAdmin : Testing log levels..

如果传入.rainbow,输出将如下所示

2021-05-09T16:17:07-0500 🟪 debug thingsAboveAdmin : Testing log levels..
2021-05-09T16:17:07-0500 🟦 info thingsAboveAdmin : Testing log levels..
2021-05-09T16:17:07-0500 🟩 notice thingsAboveAdmin : Testing log levels..
2021-05-09T16:17:07-0500 🟨 warning thingsAboveAdmin : Testing log levels..
2021-05-09T16:17:07-0500 🟧 critical thingsAboveAdmin : Testing log levels..
2021-05-09T16:17:07-0500 🟥 error thingsAboveAdmin : Testing log levels..

相关问题