D3181
D3181

Reputation: 2092

NLog log file on Xamarin - Android issues

I have been trying to use NLog from android, and it works whilst using a console based output. However when i try to target an external storage area/file nothing happens....there is no log file created...

My manifest contains the following lines:

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

My Nlog.config

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
  <targets>
    <target name="logfile" xsi:type="File" fileName="storage\emulated\0\Download\log.txt" />
  </targets>
  <rules>
    <!-- add your logging rules here -->
    <logger name="*" minlevel="Error" writeTo="logfile" />
  </rules>
</nlog>

My activity MainActivity.cs :

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Logger sm_logger = LogManager.GetCurrentClassLogger();
        sm_logger.Debug("test output");
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
    }

All of this code runs, no errors seem to be thrown, however no file is created either...using the console logger does infact output to the console however... Any help would be appreciated.

Note:

Im using both the emulator and a device, neither have a log file created.

Im building for android 7.1 level 25 of api.

The NLog.config file is bundled as a androidasset, and seems to load as it can find the targets etc

Upvotes: 3

Views: 2172

Answers (1)

John Smith
John Smith

Reputation: 2332

It is not enough to have

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

you also need to request the persmission with something like

ActivityCompat.RequestPermissions(Adapter.Activity, new String[] { Manifest.Permission.WriteExternalStorage }, 1234);

(which is incomplete, you also need to handle the permission result, but there are good resources out there on how to do that).

This needs to happen before the NLog FileTarget is created.

Upvotes: 3

Related Questions