【问题标题】:Writing logs to file using Xamarin.Forms and Serilog使用 Xamarin.Forms 和 Serilog 将日志写入文件
【发布时间】:2019-02-24 13:14:23
【问题描述】:

您好,我无法使用 Xamarin.Forms(.NET Core 共享项目)和 Serilog 将日志写入 Android 设备上的文件。

到目前为止,我已经在共享项目中安装了 Serilog。将 Serilog、Serilog.Sinks.File 和 Serilog.Sinks.Xamarin 安装到我的 Android 项目并在 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();

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

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

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

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

有什么想法吗?

【问题讨论】:

  • 挂钩 Serilog SelfLog 以查看异常 - 问题可能不是 serilog 特定的,而是与无聊的 .NET 文件 API 是否可以写入您要求的位置有关 - 尝试使用 File.WriteAllText 跨度>

标签: android xamarin logging xamarin.forms serilog


【解决方案1】:

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

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

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

       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 -&gt; app -&gt; permissions.中的权限

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

关闭应用后,可以在安卓文件管理器中看到。

【讨论】:

    【解决方案2】:

    正如 Ruben Bartelink 所指出的,问题在于 Android 不能简单地写入外部存储(即 /storage/emulated/0... 等)。 我能够在 Android 和 iOS 中登录到 Xamarin.Forms 项目中的文件。

    _Tmp = System.IO.Path.GetTempPath();            
    _Path = System.IO.Path.Combine(_Tmp, "Serilog.txt");
    
    Log.Logger = new LoggerConfiguration()
      .MinimumLevel.Debug()
      .WriteTo.File(_Path, rollingInterval: RollingInterval.Day, retainedFileCountLimit: 7)
      .CreateLogger();
    
    Log.Information("Started new serilogger {SERILOG} on file {FILE}", this, _Path);
    
    Log.CloseAndFlush();
    
    //test
    foreach (string log in System.IO.Directory.GetFiles(_Tmp, "*.txt"))
    {
        string test = System.IO.File.ReadAllText(log);
        System.Diagnostics.Debug.WriteLine($"Test[{log}] -> {test}");
    }
    

    在调试控制台上打印:

        [0:] Test[/data/user/0/com.******/cache/Serilog20190819.txt] -> 2019-08-19 16:00:36.997 +02:00 [INF] Started new serilogger ******.Functions.Serilogger on file /data/user/0/com.******/cache/Serilog.txt
    

    【讨论】:

    • 嗨@StefanoV,我想问一下你是否能够在Android的文件管理器中找到打开这个文件的方法?
    • @PaulaKristin 我无法从 Android 文件管理器打开,但我可以从应用程序内部将其作为电子邮件附件共享。我想我在某处读到文件可以通过 ADB 访问(不确定)
    • 我找到了解决方案。如果您希望我在这里分享它作为答案,请告诉我。首先,您必须在您的 Android 清单文件中允许存储权限。用户必须在运行时批准您必须编码的内容,或者您​​必须让他们更改设置 -> 应用程序 -> 权限中的权限。然后,您必须更改将链接到 `storage/emulated/0/[您添加的驱动器] 的文件名。关闭应用后,您可以在Android文件管理器中看到它。
    • 是的@PaulaKristin,一个工作样本会很有用。
    • 完成,让我知道你们的想法,请检查它是否有效。
    猜你喜欢
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多