Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use iOS OSLog with Xamarin?

How can I use the iOS OSLog in Xamarin.iOS?

I did succeed in using NSLog as follows, but I see no way of setting the subsystem (to the bundle identifier) with NSLog so that I can use that to filter the logs in 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
    }
}
like image 313
Harindaka Avatar asked Oct 29 '25 17:10

Harindaka


1 Answers

In Xamarin.iOS, there is a static CoreFoundation.OSLog object called Default that one can use straight away which will log messages with the specified OSLogLevel argument such as OSLogLevel.Debug, OSLogLevel.Error etc. You could have a method in your Xamarin.iOS code that logs a message at the Debug level:

using CoreFoundation;
// ...

public void Write(string message)
{
    OSLog.Default.Log(OSLogLevel.Debug, message);
}

If you want to use the subsystem and category, you have to instantiate an instance of OSLog using the appropriate constructor and use that instance to log your messages. Presumably you'd want to hold a static reference to your created instance and use it like you'd use 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");
        // ...
    }

This will print a fairly nice message in the device log with a timestamp and showing the specified category.

like image 187
bcr Avatar answered Oct 31 '25 05:10

bcr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!