简体   繁体   中英

Logging using Serilog from a .NET standard 1.4 class library from a UWP app

I am having trouble with a .NET standard 1.4 class library that uses Serilog to write to a json file. It runs without errors but does not produce a file.

It works fine in a .NET framework class library that is called from a .NET framework desktop app. I have the same problem when I use a UWP app with a UWP class library. Here is the code in my class library:

    public class OligoLog
    {
        public void Test()
        {
            Log.Logger = new LoggerConfiguration()
                .WriteTo.RollingFile(new CompactJsonFormatter(), @"C:\Test\log.json")
                .CreateLogger();

            Log.Information("This is a test");

            Log.CloseAndFlush();
        }
    }

Suggestions?

As @Lex Li has pointed out UWP apps do not have permission to access all files on the device. By default, apps can access certain file system locations such as application install directory or application data locations. For more info, please see File access permissions .

"C:\\Test\\log.json" is a location that you app can't directly access. While dealing with files or folders in UWP, one important rule is Skip the path: stick to the StorageFile . However, RollingFile method needs a path as the parameter. So you may store your logs into Application data locations . And LocalCacheFolder might be a good choice. Ref Using application folders :

LocalCacheFolder is under control of that app and is persistent across app sessions. LocalCacheFolder should be used for generated content needed across app sessions, such as cached files, logs, or authentication tokens.

For example:

Log.Logger = new LoggerConfiguration()
     .WriteTo.RollingFile(new CompactJsonFormatter(), Windows.Storage.ApplicationData.Current.LocalCacheFolder.Path + @"\log-{Date}.json")
    .CreateLogger();

Log.Information("This is a test");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM