考虑OSLog框架中的Logger类:Logger

由于OSLog API不允许查询调用日志(log)命令的文件名、行和函数等信息,因此我希望将这些值"嵌入"到日志(log)条目本身中.

这可以通过在Logger中添加新方法来轻松实现:

extension Logger {
func d_debug(_ message: @autoclosure () -> Any, _ file: String = #file, _ function: String = #function, line: Int = #line, context: Any? = nil) {
    let converted = (file as NSString).lastPathComponent + ":" + String(line) + ":" + function + ": " + "\(message())"
    debug("\(converted)")
}

}

这种方法的问题在于,我将不得不使用d_debug方法,而不是默认使用的标准debug方法.因此,这个修改后的方法将把实现细节"泄漏"到扩展之外.

我正在寻找一个选项来利用方法重载并使用不同的类型,即String作为输入参数,这样我的方法将成为首选方法,而不是Logger的原始LOG方法.

例如,原始签名如下所示:

    ///
    /// - Warning: Do not explicity create OSLogMessage. Instead pass a string interpolation.
    ///
    /// - Parameter message: A string interpolation.
    public func debug(_ message: OSLogMessage)

然而,我希望有这样一种方法:

func debug(_ message: @autoclosure () -> String, _ file: String = #file, _ function: String = #function, line: Int = #line) {

并对调用点完全隐藏此方法的存在这一概念(如果可能).

理想情况下,如果我删除扩展,代码应该仍然是编译的.

有没有实现这一行为的 Select ?或者像这样的任何事情都会涉及到运行时的动态修补?

推荐答案

如果我理解正确的话,您可以将您的方法命名为debug,并使用log(level:_:)方法来避免无限递归.

log(level: .debug, "\(custom)")

SWIFT会将debug(...)个调用解析为您自己的方法,而不是内置的as long as you are in the same module as the extension个.

还可以考虑使用OSLogMessage提供的自定义字符串内插.

func debug(_ message: @autoclosure () -> String, _ file: String = #file, _ function: String = #function, line: Int = #line) {
    log(level: .debug, "\((file as NSString).lastPathComponent):\(line):\(function):\(message())")
}

然而,无论采用哪种方式,调用者都不能使用OSLogMessage提供的定制字符串内插,例如定制格式、对齐和隐私.我不认为有办法实现这一点.

Swift相关问答推荐

为表单部分赋予背景 colored颜色 /渐变

字符串目录不适用于SWIFT包

如何使用AsyncTimerSequence获取初始时钟,然后在指定的时间间隔内开始迭代?

如何将多个完成处理程序转换为异步?

如何使用Duration.TimeFormatStyle以h m s格式快速格式化时间

如何使用模型在 SwiftUI 的列表中进行搜索

表视图插座单元测试失败

数组中某些元素的总和

在领域 SwiftUI 异常中使用 Apple 登录:无法识别的 Select 器发送到实例

如何在 macOS/AppKit 的窗口选项卡上接受拖动项目的放置?

需要将 json 映射到 Swift 中的模型

使用 Async-Await 和 Vapor-Fluent 创建 CRUD 函数 - Swift 5.6

SwiftUI View .tint(_ Color) 方法不起作用

如何使用 Swinject 注册符合 ObservableObject 的协议?

如何在 Swift 中将 XPC 自定义类列入白名单?

iOS Swift - 如何更改表格视图的背景 colored颜色 ?

在 Swift 中计算两个日期之间的差异

Swift:创建 UIImage 数组

在 Swift 中从服务器播放视频文件

显示 UIAlertController 的简单 App Delegate 方法(在 Swift 中)