Logging via TraceSource in Xamarin (UWP)

廉价感情. 提交于 2020-04-30 11:03:19

问题


I just want to log to console and to a log file, using a standard TraceSource, in my Xamarin app that will run on UWP, Mac OS X, iOS and Android. I'm developing/debugging on UWP.

TraceSource, TraceListener, and TextWriterTraceListener are indeed all available in .Net Standard library, so perhaps I'm setting it up incorrectly? Most places on the Internet insist on setting up trace listeners in an app.config file, but this is not applicable nor possible for Xamarin apps. So here is my logging initialization code, mostly based on an example in Microsoft docs:

        private void SetupLogging()
        {
            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out, "consoleTraceListener"));
            string logFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Application.log");
            if (!File.Exists(logFilePath)) File.Create(logFilePath);

            var logFileTraceListener = new TextWriterTraceListener(logFilePath, "logFileTraceListener");
            Trace.Listeners.Add(logFileTraceListener);

            Trace.Write("Test");
            Trace.TraceInformation("Logging Initialized. Log file location: " + logFilePath);
            Trace.Flush();
        }

When I run this in a Xamarin UWP app, a file is created but nothing is written to it, nor can I find anything in the Output of the program (there is no ConsoleTraceListener so I'm trying to write a TextWriterTraceListener to Console.Out). Can someone provide a working example for Xamarin? (I haven't tried the Android or iOS apps yet; want to get UWP on the local machine working first.)


回答1:


The problem is that you passed wrong string parameter to TextWriterTraceListener method. Please try to pass Stream parameter. You could use following code directly. by the way, you'd better use LocalApplicationData SpecialFolder that could be accessed successfully within uwp.

private void SetupLogging()
{
    Trace.Listeners.Add(new TextWriterTraceListener(Console.Out, "consoleTraceListener"));
    string logFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Application.log");
    if (!File.Exists(logFilePath))
    {
        File.Create(logFilePath);
    }
    var logFileTraceListener = new TextWriterTraceListener(File.Open(logFilePath,FileMode.Open), "logFileTraceListener");
    Trace.Listeners.Add(logFileTraceListener);

    Trace.Write("Test");
    Trace.TraceInformation("Logging Initialized. Log file location: " + logFilePath);
    Trace.Flush();
}


来源:https://stackoverflow.com/questions/55243997/logging-via-tracesource-in-xamarin-uwp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!