2

I am writing an uwp app with C# and I would like to use serilog to write logfiles. When I do it in a .NET Core Console application it creates the file with the wanted content.

In the uwp I can show the log messages on the GUI, but no log file is created (yes, I have broadFileSystemAccess).

My code:

Log.Logger = new LoggerConfiguration().WriteTo.File("log.txt").CreateLogger();
Log.Debug("TEST");
Log.CloseAndFlush();

I would expect that it creates log.txt file in the directory which can be get with Windows.Storage.ApplicationData.Current.LocalFolder like

storageFolder.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);

does.

Question: What do I need to change to log into a file using verilog in my uwp app?

2 Answers 2

4

One of the great things about Serilog is that it's open-source and you can look at its source code and see what it is doing / how it works.

If you peek at the source code of the File sink, you'll notice that it is simply opening a file via System.IO.File.Open on the same folder where your app is running, which running from Visual Studio is probably going to be something like C:\Users\augustoproiete\MyApp\MyUwpApp\bin\x64\Debug\AppX\ where you don't have access to write file.

That means you have to be explicit about where to store the file, for example in the application data folder of your app. E.g.:

var logFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "log.txt");

Log.Logger = new LoggerConfiguration().WriteTo.File(logFilePath).CreateLogger();
Log.Debug("TEST");
Log.CloseAndFlush();

I'd recommend you read the Debugging and Diagnostics page on Serilog's docs, as it explains how you see error messages from Serilog - which you'd have seen that it was failing to create a file and the path it was using.

Sign up to request clarification or add additional context in comments.

Comments

1

Thank yu for your answer!

I thought that the local folder path is automatically used, so I did not try that. I jus had to modify the code as follows

var logFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "log.txt");

Log.Logger = new LoggerConfiguration()
                 .MinimumLevel.Verbose()     //otherwise Debug is not logged
                 .WriteTo.File(logFilePath)
                 .CreateLogger();
Log.Debug("TEST");
Log.CloseAndFlush();

then it woked and wrote the Debug message to the log file :)

Thank you very much!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.