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.)
答案 0 :(得分:1)
问题是您将错误的字符串参数传递给TextWriterTraceListener
方法。请尝试传递Stream
参数。您可以直接使用以下代码。顺便说一句,您最好使用LocalApplicationData
SpecialFolder,它可以在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();
}