使用 Xamarin.Forms 和 Serilog 将日志写入文件 [英] Writing logs to file using Xamarin.Forms and Serilog

查看:316
本文介绍了使用 Xamarin.Forms 和 Serilog 将日志写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我在使用 Xamarin.Forms(.NET Core 共享项目)和 Serilog 在 Android 设备上将日志写入文件时遇到问题.

Hello I am having trouble writing logs to file on Android device using Xamarin.Forms (.NET Core shared project) and Serilog.

到目前为止,我已经在共享项目中安装了 Serilog.将 Serilog、Serilog.Sinks.File 和 Serilog.Sinks.Xamarin 安装到我的 Android 项目中并在 MainActivity 中初始化记录器:

So far I have installed Serilog in Shared project. Installed Serilog, Serilog.Sinks.File, and Serilog.Sinks.Xamarin to my Android project and initialized logger in MainActivity:

Log.Logger = new LoggerConfiguration()
        .WriteTo.File(Path.Combine(Environment.ExternalStorageDirectory.AbsolutePath,"XamarinLib-{Date}.txt"),
                        outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] {Message}{NewLine}{Exception}",
                        fileSizeLimitBytes: 100000000,
                        rollingInterval: RollingInterval.Day,
                        rollOnFileSizeLimit: true,
                        shared: false,
                        retainedFileCountLimit: 31,
                        encoding: Encoding.UTF8)
                    .WriteTo.AndroidLog()
                    .CreateLogger();

之后我从共享项目中调用记录器,例如:

Afterwards I call the logger from shared project like:

Log.Information("Test writing to log file");

我可以在 Visual Studio 调试输出中看到正在执行的日志命令,但根本没有创建该文件.我已经在模拟器和实际设备上尝试了多个位置(没有 root 访问权限).

I can see the log command being executed in Visual Studio debug output, but the file is simply not created. I've tried multiple locations on both emulator and actual device (no root access).

我也尝试过以类似的方式使用 RollingFile 接收器,但没有成功.

I've also tried to use RollingFile sink in similar manner with no success.

有什么想法吗?

推荐答案

首先,您必须在 AndroidManifest.xml 文件中允许权限.

First, you have to allow permissions in your AndroidManifest.xml file.

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

接下来,用户必须在运行时批准,您必须在后面的代码中对此进行编码.注意记得在你的 NUGET 包上添加 Plugin.Permissions:

Next, The user either must, approve that on runtime in which you have to code this in your code behind. NOTE Remember to add Plugin.Permissions on your NUGET package:

       InitializeComponent();

        Task.Run(async () =>
        {
            try
            {
                var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
                if (status != PermissionStatus.Granted)
                {
                        var accepted = await DisplayAlert("Storage Permission Required",
                            "Please enable your storage permission, it will be used to store logs and crashes",
                            "ACCEPT",
                            "CANCEL");
                        if(accepted)
                        {
                            var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Storage);
                            status = results[Permission.Storage];
                        }
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Exception ex", "Exception ex", "OK");
            }
        });

让他们在 settings 中更改权限 ->应用程序->权限.

最后,更改将链接到 storage/emulated/0/[your added directory] 的文件名.

Finally, change the filename that will link to the storage/emulated/0/[your added directory].

关闭应用后,您可以在 Android 文件管理器中看到它.

After the closing the app, you can see it in the Android File Manager.

这篇关于使用 Xamarin.Forms 和 Serilog 将日志写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆