在控制台日志中使用带颜色的print()。

44

代码如下:

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

我也阅读了这篇文章:使用Swift命令行工具输出颜色,但似乎不起作用。
我不想使用库。

5
正如在链接的问答中提到的,在终端窗口运行程序时,设置颜色是有效的,但在Xcode控制台中。 - Martin R
6
这里也确认了 https://dev59.com/uWox5IYBdhLWcg3wvWsy: "......由于Xcode调试控制台似乎不支持着色。" - Martin R
Xcode的终端窗口不支持着色。它的$TERM值为nil。在Xcode的调试器区域中没有办法使用颜色。但是,您可以附加另一个终端作为输出(在Xcode的首选项中),在那里,输出将支持颜色。 - Eric Aya
@ZonilyJame 如果您选择关闭它,请不要忘记验证我的答案。 - Danyl
1
@DanylS 我不会关闭它,但我会将您放置为答案,因为我们永远不知道下一次 Xcode 迭代是否会有变化。 - Zonily Jame
显示剩余4条评论
8个回答

62

Xcode自Xcode 8以来不支持控制台着色。

但是由于Xcode完全支持Unicode,您可以使用表情符号来代替!例如,您可以使用⚠️表示警告信息,表示错误消息。(就像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

单词搜索

单词搜索


1
太有创意了!从来没有想过这个!哈哈哈,谢谢! - Arturo
1
非常好用,即使在流水线上的构建机器上也能正常工作! - Async-

37

现在,Xcode调试控制台不支持着色。


1
还有其他选项可用吗? - user4003752
1
这个项目可能会给你一些希望:XcodeColors - Leslie Godwin
一个为日志上色的替代方案**在此处描述**。 - Mojtaba Hosseini

7

除了@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")

您正在使用特殊的Unicode字符。最好将它们提供为转义序列,以避免在代码中使用Unicode。 - Xypron
非常好的答案和解决方案! - ytpm

2
正如@LeslieGodwin所提到的,XcodeColors是一款用于Xcode控制台的插件,它为Xcode版本低于8的用户添加了颜色支持。

虽然这个链接可能回答了问题,但最好在这里包含答案的关键部分,并提供链接作为参考。仅有链接的答案可能会因为链接页面的变动而失效。- 来自审查 - undefined
我的回答只适用于Xcode 8版本。目前来说,这已经是一个过时的Xcode版本了。 - undefined

2

添加我的贡献:

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”更改图标


1
如果你正在寻找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..

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

默认情况下,生产环境仅记录错误日志,但当然很容易进行配置。

可能有更好或更优雅的方法来实现这一点,但对我而言它是有效的。


这里建议使用枚举而非字符串来表示级别。 - HangarRash

-1

Xcode控制台颜色主题/方案

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

这并不能真正解决这里的问题,因为目标是将一些日志或部分日志以不同的颜色突出显示,以便更容易地发现它们。 - La pieuvre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接