如何将 iOS OSLog 与 Xamarin 结合使用?

Har*_*aka 4 nslog xamarin.ios ios xamarin

如何在 Xamarin.iOS 中使用 iOS OSLog

我确实成功地使用了 NSLog,如下所示,但我看不到如何使用 NSLog 设置子系统(到包标识符),以便我可以使用它来过滤 Console.app 中的日志。

public class Logger
{
    #if DEBUG
    [DllImport(ObjCRuntime.Constants.FoundationLibrary)]
    private extern static void NSLog(IntPtr message);
    #endif

    public void WriteLine(string line)
    {
        #if DEBUG
        using (var nss = new NSString(line))
        {
            NSLog(nss.Handle);
        }
        #endif
    }
}
Run Code Online (Sandbox Code Playgroud)

bcr*_*bcr 5

在 中Xamarin.iOS,有一个CoreFoundation.OSLog名为 的静态对象Default,可以立即使用,它将使用指定的OSLogLevel参数(例如等OSLogLevel.Debug)记录消息OSLogLevel.Error。您可以在Xamarin.iOS代码中使用一个方法来记录以下级别的消息Debug

using CoreFoundation;
// ...

public void Write(string message)
{
    OSLog.Default.Log(OSLogLevel.Debug, message);
}
Run Code Online (Sandbox Code Playgroud)

如果您想使用子系统和类别,则必须OSLog使用适当的构造函数实例化一个实例,并使用该实例来记录消息。想必您希望保留对创建的实例的静态引用并像使用OSLog.Default.

public partial class AppDelegate : Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    public static OSLog LoggerInstance;

    public override bool FinishedLaunching(UIApplication app, NSDictionary launchOptions)
    {
        LoggerInstance = new OSLog(subsystem: "subsystem", category: "category");
//...

public class SomeClass
{
    public void SomeMethod()
    {
        AppDelegate.LoggerInstance?.Log(OSLogLevel.Debug, "log message");
        // ...
    }
Run Code Online (Sandbox Code Playgroud)

这将在设备日志中打印一条相当不错的消息,其中包含时间戳并显示指定的类别。