【问题标题】:How to config `Serilog` to write to the application directory with the cofig file?如何配置 `Serilog` 以使用配置文件写入应用程序目录?
【发布时间】:2019-04-02 12:26:47
【问题描述】:

我在.net core 上使用Serilog。 我想配置应用程序目录的日志路径。

我看到有一个扩展 https://github.com/serilog/serilog-settings-configuration 使 Serilog 能够从 Configuration 读取。 在示例中,路径配置为"%TEMP%\\Logs\\serilog-configuration-sample.txt"。 如何将其设置为工作目录?

我已经搜索过了,并且知道可以通过代码完成,但似乎没有人询问如何通过配置文件执行此操作,即appsettings.json

当前配置:

{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.File"
    ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "File",
        "Args": { "path": "Logs\\serilog-configuration-sample.txt" }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName" ],
    "Destructure": [
    ],
    "Properties": {
    }
  },
  "AllowedHosts": "*"
}

我希望将日志路径设置为工作目录。 但目前它位于“C:\Program Files\IIS Express”中。

【问题讨论】:

  • 如果我没记错的话,应该可以为WriteTo 参数定义一个绝对路径!?因此,您可以使用Environment.SetEnvironmentVariable("MY_APP_DIR", MyAppDir) 为您的应用程序定义一个环境变量,并将“%MY_APP_DIR%\\Logs\\serilog-configuration-sample.txt”定义为您的输出路径...
  • @Robert 谢谢你,这行得通。我认为应该有一种方法可以直接通过配置文件进行配置,但它似乎是目前使用环境变量的唯一方法......

标签: c# .net-core serilog


【解决方案1】:

配置Logs/log.txt这样的路径会在工作目录的logs文件夹下写入日志文件

"WriteTo": [
  {
    "Name": "File",
    "Args": {
      "path": "Logs/log.txt"
    }
  }

您也可以查看this answer 以获取其他选项

【讨论】:

  • 这个答案中的方法似乎没有效果......但是您提供的使用环境变量的链接对我有用。
  • @mosakashaka 我可以知道您使用的是哪个版本的 .Net Core 吗?
【解决方案2】:

您可以添加一个“RollingFile”,它可以写入本地路径文件。在此示例中,我正在项目根目录内的文件中写入,如下所示。

{
    "Name": "RollingFile",
    "Args": {
      "pathFormat": ".\\Logs\\logs.txt",
      "fileSizeLimitBytes": 1048576
    }
  },

appsettings.json 上的完整 json 也会像这样结束(以防您需要完整示例)

...
"Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "System": "Debug",
        "Microsoft": "Debug"
      }
    },
    "WriteTo": [
      {
        "Name": "ApplicationInsightsEvents",
        "Args": {
          "instrumentationKey": "xxxxxxxxxx"
        }
      },
      {
        "Name": "RollingFile",
        "Args": {
          "pathFormat": ".\\Logs\\logs.txt",
          "fileSizeLimitBytes": 1048576
        }
      },
      { "Name": "Console" },
      {
        "Name": "EventLog",
        "Args": {
          "source": "API NAME",
          "logName": "CustomLog",
          "restrictedToMinimumLevel": "Warning"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "Properties": {
      "Application": "API NAME"
    }
  }
...

【讨论】:

  • 在路径前加点号好像没有效果....当我在visual studio中调试时,日志仍在写入IIS目录...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多