Click here to Skip to main content
15,867,835 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi ,
i used nlog to get log in xamarinform but the nlog not loged any thing
whats problem?

What I have tried:

nlog.config:
XML
<pre><?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">

  <targets>
    <target name="logfile"
        xsi:type="File"
        fileName="${specialfolder:folder=LocalApplicationData}/logs/nlog.csv"
	    
        archiveFileName="${specialfolder:folder=LocalApplicationData}/logs/nlog-{#}.csv"
        archiveEvery="Hour"
        archiveNumbering="Date"
        maxArchiveFiles="5"
        archiveDateFormat="yyyy-MM-dd-HH-mm"
        encoding="UTF-8">
      <layout xsi:type="CSVLayout">
        <quoting>All</quoting>
        <withHeader>true</withHeader>
        <delimiter>Comma</delimiter>
        <column name="time" layout="${longdate}" />
        <column name="logger" layout="${logger}"/>
        <column name="level" layout="${level}"/>
        <column name="machinename" layout="${machinename}"/>
        <column name="windows-identity" layout="${windows-identity}"/>
        <column name="appdomain" layout="${appdomain}"/>
        <column name="processid" layout="${processid}"/>
        <column name="processname" layout="${processname}"/>
        <column name="threadid" layout="${threadid}"/>
        <column name="message" layout="${message}" />
        <column name="stacktrace" layout="${exception:format=Type,Message,StackTrace,Data:maxInnerExceptionLevel=5}" />
      </layout>
    </target>
    <target xsi:type="Console" name="console" layout="${longdate} ${uppercase:${level}} ${message}" />
  </targets>
  <rules>
    <!-- Available LogLevels: Trace, Debug, Info, Warn, Error and Fatal -->
    <logger rulename="logfilelogger" name="*" minlevel="Warn" writeTo="logfile" />
    <logger rulename="consolelogger" name="*" minlevel="Debug" writeTo="console" />
  </rules>

</nlog>




interface:

C#
using System.Reflection;

namespace MyApp.Interfaces
{
    public interface ILogService
    {
        void Initialize(Assembly assembly, string assemblyName);
    }
}


impeliment interface:
C#
public class LogService : ILogService
   {
       public void Initialize(Assembly assembly, string assemblyName)
       {
           string resourcePrefix;

           if (Device.RuntimePlatform == Device.iOS)
               resourcePrefix = "_sapmletask.iOS";
           else if (Device.RuntimePlatform == Device.Android)
               resourcePrefix = "_sapmletask.Droid";
           else
               throw new Exception("Could not initialize Logger: Unknonw Platform");

           //var location = $"{assemblyName}.NLog.config";

           string location = $"{resourcePrefix}.NLog.config";
           Stream stream = assembly.GetManifestResourceStream(location);
           if (stream == null)
               throw new Exception($"The resource '{location}' was not loaded properly.");

           LogManager.Configuration = new XmlLoggingConfiguration(System.Xml.XmlReader.Create(stream), null);
       }
   }




main:
C#
private readonly NLog.ILogger _logger = NLog.LogManager.GetCurrentClassLogger();

    public MainPage()
    {
        InitializeComponent();
        _logger.Info("im  was here");
        _logger.Debug("im  was here");
        _logger.Info("Application Start.");


    }



activity:
C#
protected override void OnCreate(Bundle savedInstanceState)
       {
           TabLayoutResource = Resource.Layout.Tabbar;
           ToolbarResource = Resource.Layout.Toolbar;

           base.OnCreate(savedInstanceState);

           Xamarin.Essentials.Platform.Init(this, savedInstanceState);
           global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

           InitializeNLog();
           LoadApplication(new App());
       }

       private void InitializeNLog()
       {
           Assembly assembly = this.GetType().Assembly;
           string assemblyName = assembly.GetName().Name;
           new Helpers.LogService().Initialize(assembly, assemblyName);
       }
Posted
Updated 20-Oct-21 20:45pm

1 solution

Your logging rule for the file-target is only enabled for warn-/error-logging. Maybe update your main-method to log an Error-event. Else you will only get output to console.

Also make sure that Nlog.config is loaded correctly from assembly resource as described here

Loading NLog configuration from Xamarin resource[^]

Remember to explicitly configure ConcurrentWrites=false for the file target. And that you can use NLog InternalLogger for troubleshooting

Internal Logging · NLog/NLog Wiki · GitHub[^]
 
Share this answer
 
v2
Comments
mohamad_ali 21-Oct-21 9:12am    
I‘m not sure, i changed many things, but i thing problem was where the logs were stored
Rolf Kristensen 21-Oct-21 13:17pm    
The question was why no output from NLog. The answer is usually to ensure NLog.config is loaded (hence my advice about using assembly resource). And secondly to fix target issues like file-permissions (hence my advice about checking NLog InternalLogger for errors). If you now have a different errors, then you should update your question.
mohamad_ali 22-Oct-21 3:00am    
nlog was be loaded and as i said before, i chenged alot of things, and finally got the output and the problem was solved, but im not sure wich one it was,(the most important change was the relocation of the log output)
Rolf Kristensen 22-Oct-21 3:03am    
Sounds like you should make an answer to your own question with the updated NLog.config that is working for you
mohamad_ali 22-Oct-21 3:45am    
i thing this chenge solved the problem
in manifest i chenged :
before :package="com.companyname.sampletask"
after: package="SampleTask.Android"
and the file name : fileName="/data/data/SampleTask.Android/logs/Nnlog.csv"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900