简体   繁体   English

使用来自 UWP 应用程序的 .NET 标准 1.4 类库中的 Serilog 进行日志记录

[英]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.我遇到了使用 Serilog 写入 json 文件的 .NET 标准 1.4 类库的问题。 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.它在从 .NET 框架桌面应用程序调用的 .NET 框架类库中运行良好。 I have the same problem when I use a UWP app with a UWP class library.当我使用带有 UWP 类库的 UWP 应用程序时,我遇到了同样的问题。 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.正如@Lex Li 指出的,UWP 应用程序无权访问设备上的所有文件。 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. "C:\\Test\\log.json"是您的应用无法直接访问的位置。 While dealing with files or folders in UWP, one important rule is Skip the path: stick to the StorageFile .在 UWP 中处理文件或文件夹时,一条重要规则是跳过路径:坚持使用 StorageFile However, RollingFile method needs a path as the parameter.但是, RollingFile方法需要一个路径作为参数。 So you may store your logs into Application data locations .因此,您可以将日志存储到应用程序数据位置 And LocalCacheFolder might be a good choice.LocalCacheFolder可能是一个不错的选择。 Ref Using application folders :参考使用应用程序文件夹

LocalCacheFolder is under control of that app and is persistent across app sessions. LocalCacheFolder受该应用程序的控制并且在应用程序会话中是持久的。 LocalCacheFolder should be used for generated content needed across app sessions, such as cached files, logs, or authentication tokens. LocalCacheFolder应用于跨应用程序会话所需的生成内容,例如缓存文件、日志或身份验证令牌。

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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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