Logger for Windows 10 UWP app

27,376

Solution 1

Have you tried MetroLog? You can install it using NuGet:

Install-Package MetroLog

Here's an quick example:

using MetroLog;
using MetroLog.Targets;

LogManagerFactory.DefaultConfiguration.AddTarget(LogLevel.Trace, LogLevel.Fatal, new FileStreamingTarget());

ILogger log = LogManagerFactory.DefaultLogManager.GetLogger<MainPage>();

log.Trace("This is a trace message.");

You can find a tutorial explaining how to add it on your project at http://talkitbr.com/2015/06/11/adicionando-logs-em-universal-apps. Also there is an explanation regarding retrieving these logs.

Solution 2

Serilog

One possibility is to use Serilog as an central logging interface and configure it to have an Sink that works with UWP.

You can use one of the many Sinks you can choose from, but you can also opt to use your own logging infrastructure by implementing a custom sink.

To make it even more useful, you can use Anotar.Serilog.Fody to use the Fody Code Weaver and use Aspects to make your logging trivial.

Typically you want to use a central logging provider for Application Lifecycle Management (ALM), as well as a local sink (File) as fallback for fatal errors.

MetroLog

MetroLog is a simple logging infrastructure on top of ETW and LocalState. This is fast and easy to implement, but it does not help you with ALM, since centralized logging is not supported.

UWP Logging

Universal Windows Plattform Logging is relatively new and only possible with Windows 10 and Windows Server 2016. You can choose between ETW and LocalStorage. It gives you most low-level-control about how your log should look like, but naturally also causes the most work to implement and also lacks ALM capabilities.

Helpful Links

Solution 3

If you would like to log to a file and take advantage of the Microsoft's lightweight DI framework you can use Serilog.

In Nuget Package Manager Console enter the following:

Install-Package Microsoft.Extensions.DependencyInjection
Install-Package Microsoft.Extensions.Logging
Install-Package Serilog.Extensions.Logging.File

Set up dependency injection container at the composition root. In our case it is OnLaunched method in the App.xaml.cs file.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Windows.Storage;
...

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
     ...
    // Create IOC container and add logging feature to it.
    IServiceCollection services = new ServiceCollection();
    services.AddLogging();

    // Build provider to access the logging service.
    IServiceProvider provider = services.BuildServiceProvider();

    // UWP is very restrictive of where you can save files on the disk.
    // The preferred place to do that is app's local folder.
    StorageFolder folder = ApplicationData.Current.LocalFolder;
    string fullPath = $"{folder.Path}\\Logs\\App.log";

    // Tell the logging service to use Serilog.File extension.
    provider.GetService<ILoggerFactory>().AddFile(fullPath);
    ...
}

Once set up, logging is very simple. Just inject the logger into your class.

using Microsoft.Extensions.Logging;

class MyClass
{
    readonly ILogger<MyClass> logger;

    public MyClass(ILogger<MyClass> logger)
    {
        this.logger = logger;
        logger.LogInformation("Hello from MyClass.");
    }
}

Your log file should be created in:

C:\Users\yourUserName\AppData\Local\Packages\f15fdadf-faae-4f4a-8445-5feb195ff692_68newbw0j54vy\LocalState\Logs\App-20171206.log,

where f15fdadf-faae-4f4a-8445-5feb195ff692_68newbw0j54vy is the package name from the Package.appxmanifest file in my solution.

Please note that AppData folder is hidden in File Explorer by default.

And here is its content:

2017-12-06T17:06:33.1358005-06:00  [INF] Hello from MyClass. (25278b08)

Solution 4

The only solution I know is to use the APIs in windows.foundation.diagnostics namespace to do ETW tracing.

And Microsoft has provided a sample here.

Solution 5

You can use the standard Serilog rolling file sink in UWP, you just need to tell the logger where to log to. Here's some code to set that up (I'm using Autofac);

private static void RegisterLogger(ContainerBuilder builder)
{
    const string fileOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level}] {Message}{NewLine}{Exception}";
    var logPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "Logs", "MyAppName-{Date}.log");

    var logConfiguration = new LoggerConfiguration()
                            .MinimumLevel.Verbose()
                            .WriteTo.RollingFile(logPath, outputTemplate: fileOutputTemplate);

    Log.Logger = logConfiguration.CreateLogger();

    builder.RegisterLogger();
}

```

Share:
27,376
Rashmin Javiya
Author by

Rashmin Javiya

"Understand Problem, Learn Concept" Curious to learn new technologies. Passionate about programming, web design and algorithm optimization. Currently working in the Asp MVC Rich Internet Application with Microsoft Entity Framework and jQuery. More about me @ http://rashm.in #SOreadytohelp

Updated on July 28, 2022

Comments

  • Rashmin Javiya
    Rashmin Javiya almost 2 years

    I couldn't found any loggers for windows 10 universal app, i have tried out log4net, Microsoft enterprise library, Nlog but none of them are supported in windows 10 Universal platform.

    Can anyone suggest me good logger for the windows 10 UWP?