简体   繁体   English

如何让Serilog从appsettings.json登录到web输出目录?

[英]How to get Serilog to log to the web output directory from appsettings.json?

I created a new .NET Core web project using Visual Studio and integrated Serilog. 我使用Visual Studio和集成的Serilog创建了一个新的.NET Core Web项目。 It reads settings from the appsettings.json (via .UseSerilog((ctx, config) => { config.ReadFrom.Configuration(ctx.Configuration); }) ). 它从appsettings.json读取设置(通过.UseSerilog((ctx, config) => { config.ReadFrom.Configuration(ctx.Configuration); }) )。

In the appsettings.json, the path to write the log is specified at Serilog/WriteTo/Args/pathFormat . 在appsettings.json中,写入日志的路径在Serilog/WriteTo/Args/pathFormat If I set that value to log.txt , it will attempt to write the file to `c:\\program files\\iisexpress\\log.txt'. 如果我将该值设置为log.txt ,它将尝试将该文件写入`c:\\ program files \\ iisexpress \\ log.txt'。

How can I get it to write to the content root of my web app? 如何让它写入我的网络应用程序的内容根目录?

Ideally, you don't want to write log files to the content root of your web app, since these could end up being accessible over the web, which would be a serious security consideration. 理想情况下,您希望将日志文件写入Web应用程序的内容根目录,因为这些文件最终可以通过Web访问,这将是一个严重的安全考虑因素。

The log file path configuration can include environment variables, so something like %TMP%\\log.txt , or a path based on %LOCALAPPDATA% etc. is a good option (as long as the web site's worker process has permission to write to the location). 日志文件路径配置可以包含环境变量,因此%TMP%\\log.txt或基于%LOCALAPPDATA%等的路径是一个不错的选择(只要网站的工作进程有权写入地点)。

You can write to a path that's relative to your web app by changing the current directory before setting up the logger: 在设置记录器之前,您可以通过更改当前目录来写入与Web应用程序相关的路径:

Environment.CurrentDirectory = AppContext.BaseDirectory;

Or, you can combine these approaches and set your own environment variable to do it: 或者,您可以组合这些方法并设置自己的环境变量来执行此操作:

Environment.SetEnvironmentVariable("BASEDIR", AppContext.BaseDirectory);

Thus the following config: 因此以下配置:

"%BASEDIR%\logs\log.txt"

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

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